<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能数据引擎</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        // 主色调
                        primary: '#3b82f6',
                        light: 'rgba(248, 250, 252, 0.96)',
                        mid: 'rgba(226, 232, 240, 0.94)',
                        dark: 'rgba(148, 163, 184, 0.92)',
                        hover: 'rgba(59, 130, 246, 0.15)',
                        border: 'rgba(59, 130, 246, 0.4)',
                        bg: '#f8fafc',
                        main: 'rgba(59, 130, 246, 0.15)',
                        accent: '#3b82f6',
                        // 文本色彩
                        text: {
                            primary: '#334155',
                            secondary: '#64748b',
                            accent: '#3b82f6',
                            light: '#94a3b8'
                        },
            corePlugins: {
                preflight: false // 禁用默认重置样式，避免与现有CSS冲突
            },
                        // 功能色彩
                        success: '#10b981',
                        danger: '#ef4444',
                        warning: '#f59e0b',
                        info: '#3b82f6'
                    },
                    fontFamily: {
                        sans: ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 'sans-serif']
                    },
                    borderRadius: {
                        small: '8px',
                        medium: '12px',
                        large: '16px',
                        circle: '50%'
                    },
                    boxShadow: {
                        default: '0 4px 12px rgba(0, 0, 0, 0.02)',
                        hover: '0 6px 16px rgba(0, 0, 0, 0.04)',
                        active: '0 8px 20px rgba(0, 0, 0, 0.06)'
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.6s ease-out',
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite'
                    },
                    keyframes: {
                        fadeIn: {
                            '0%': { opacity: '0' },
                            '100%': { opacity: '1' }
                        }
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            /* 仅保留必要的工具类，避免与原生CSS冲突 */
            .content-auto {
                content-visibility: auto;
            }
            .text-balance {
                text-wrap: balance;
            }
        }
    </style>
    <style>
        /* 基础样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* 色彩系统 - 冷静蓝色背调主题 */
        :root {
            /* 6级色彩层次 */
            --color-light: rgba(248, 250, 252, 0.96);
            --color-mid: rgba(226, 232, 240, 0.94);
            --color-dark: rgba(148, 163, 184, 0.92);
            --color-hover: rgba(59, 130, 246, 0.15);
            --color-border: rgba(59, 130, 246, 0.4);
            --color-bg: #f8fafc;
            --color-main: rgba(59, 130, 246, 0.15);
            --color-accent: #3b82f6;
            
            /* 文本色彩 */
            --color-text-primary: #334155;
            --color-text-secondary: #64748b;
            --color-text-accent: #3b82f6;
            --color-text-light: #94a3b8;
            
            /* 功能色彩 */
            --color-success: #10b981;
            --color-danger: #ef4444;
            --color-warning: #f59e0b;
            --color-info: #3b82f6;
            
            /* 阴影 */
            --shadow-default: 0 4px 12px rgba(0, 0, 0, 0.02);
            --shadow-hover: 0 6px 16px rgba(0, 0, 0, 0.04);
            --shadow-active: 0 8px 20px rgba(0, 0, 0, 0.06);
            
            /* 圆角 */
            --radius-small: 8px;
            --radius-medium: 12px;
            --radius-large: 16px;
            --radius-circle: 50%;
            
            /* 间距 - 主要间距5-9，内边距6-8（相对单位） */
            --spacing-xs: 0.25rem;
            --spacing-sm: 0.5rem;
            --spacing-md: 0.75rem;
            --spacing-lg: 1rem;
            --spacing-xl: 1.5rem;
            --spacing-2xl: 2rem;
            
            /* 动画时长 */
            --transition-fast: 0.2s;
            --transition-normal: 0.3s;
            --transition-slow: 0.5s;
        }

        /* 背景网格图案 - 20px×20px，透明度5% */
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
                'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
            background-color: var(--color-bg);
            color: var(--color-text-primary);
            line-height: 1.6;
            background-image: linear-gradient(to right, rgba(59, 130, 246, 0.05) 1px, transparent 1px),
                            linear-gradient(to bottom, rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            animation: fadeIn 0.6s ease-out;
            overflow-x: hidden;
            margin: 0;
            padding: 0;
        }

        /* 文本选择颜色 */
        ::selection {
            background-color: var(--color-hover);
            color: var(--color-text-accent);
        }

        /* 滚动条样式优化 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--color-light);
            border-radius: var(--radius-small);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--color-border);
            border-radius: var(--radius-small);
            transition: background var(--transition-normal);
        }

        /* 通知系统样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .toast {
            padding: 12px 20px;
            border-radius: var(--radius-small);
            color: white;
            font-size: 0.9rem;
            font-weight: 500;
            box-shadow: var(--shadow-active);
            opacity: 0;
            transform: translateX(100%);
            transition: all var(--transition-normal) ease-out;
            display: flex;
            align-items: center;
            gap: 8px;
            max-width: 300px;
            backdrop-filter: blur(4px);
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success {
            background-color: rgba(16, 185, 129, 0.95);
        }

        .toast-error {
            background-color: rgba(239, 68, 68, 0.95);
        }

        .toast-warning {
            background-color: rgba(245, 158, 11, 0.95);
        }

        .toast-info {
            background-color: rgba(59, 130, 246, 0.95);
        }

        .toast-close {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 1.2rem;
            margin-left: auto;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0.7;
            transition: opacity var(--transition-fast);
        }

        .toast-close:hover {
            opacity: 1;
        }

        /* 加载状态组件 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.7);
            backdrop-filter: blur(4px);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            transition: all var(--transition-normal);
        }

        .loading-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .loading-spinner {
            width: 48px;
            height: 48px;
            border: 4px solid var(--color-mid);
            border-top: 4px solid var(--color-accent);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16px;
        }

        .loading-text {
            color: var(--color-text-secondary);
            font-size: 0.9rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--color-dark);
        }

        /* Main container styles moved to inline styles */

        /* 标题样式 - 排版规范 */
        .page-title {
            font-size: clamp(1.5rem, 3vw, 2rem);
            color: var(--color-text-primary);
            margin-bottom: var(--spacing-lg);
            font-weight: 600;
            text-wrap: balance;
            animation: fadeIn 0.8s ease-out;
        }

        /* 中标题样式 */
        h2 {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--color-text-primary);
            margin-bottom: var(--spacing-md);
            text-wrap: balance;
        }

        /* 小标题样式 */
        h3 {
            font-size: 1rem;
            font-weight: 500;
            color: var(--color-text-primary);
            margin-bottom: var(--spacing-sm);
        }

        /* 卡片样式 - 玻璃态设计 */
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid var(--color-border);
            border-radius: var(--radius-medium);
            padding: var(--spacing-md);
            margin-bottom: var(--spacing-lg);
            box-shadow: var(--shadow-default);
            transition: all var(--transition-normal) ease;
            backdrop-filter: blur(20px);
            position: relative;
            overflow: hidden;
        }

        /* 卡片悬停效果 - 上移2px，阴影加深 */
        .card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-sm);
            padding-bottom: var(--spacing-xs);
            border-bottom: 1px solid var(--color-mid);
        }

        .card-title {
            font-size: 1.25rem;
            font-weight: 500;
            color: var(--color-text-primary);
        }

        /* 标签页样式 - 激活状态指示：左侧3px宽垂直条 */
        .tabs {
            display: flex;
            gap: var(--spacing-sm);
            margin-bottom: var(--spacing-md);
            border-bottom: 1px solid var(--color-border);
            position: sticky;
            top: 0;
            background-color: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(20px);
            padding: var(--spacing-sm) 0;
            z-index: 10;
            overflow-x: auto;
            scrollbar-width: thin;
        }

        .tab {
            padding: var(--spacing-xs) var(--spacing-sm);
            cursor: pointer;
            border: none;
            background: none;
            color: var(--color-text-secondary);
            font-size: 0.9rem;
            position: relative;
            transition: all var(--transition-normal) ease;
            white-space: nowrap;
            border-left: 3px solid transparent;
        }

        .tab:hover:not(.active) {
            color: var(--color-text-primary);
            background-color: var(--color-hover);
        }

        .tab.active {
            color: var(--color-text-accent);
            font-weight: 500;
            border-left-color: var(--color-accent);
            background-color: var(--color-hover);
        }

        .tab.active::after {
            display: none;
        }

        .tab-content {
            display: none;
            animation: fadeIn var(--transition-normal) ease-out;
        }

        .tab-content.active {
            display: block;
        }

        /* 按钮样式 - 微交互 */
        .btn {
            padding: var(--spacing-xs) var(--spacing-sm);
            border: none;
            border-radius: var(--radius-small);
            cursor: pointer;
            font-size: 0.9rem;
            transition: all var(--transition-normal) ease;
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-xs);
            position: relative;
            overflow: hidden;
            user-select: none;
        }

        /* 按钮悬停效果 - 背景色切换，过渡时间0.3s */
        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left var(--transition-slow);
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background-color: var(--color-accent);
            color: white;
        }

        .btn-primary:hover {
            background-color: #2563eb;
            transform: translateY(-1px);
            box-shadow: var(--shadow-default);
        }

        .btn-secondary {
            background-color: var(--color-mid);
            color: var(--color-text-primary);
        }

        .btn-secondary:hover {
            background-color: var(--color-dark);
            transform: translateY(-1px);
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--color-border);
            color: var(--color-text-primary);
        }

        .btn-outline:hover {
            background-color: var(--color-hover);
            border-color: var(--color-accent);
            transform: translateY(-1px);
        }

        /* 输入框样式 - 聚焦时2px浅色边框 */
        .input-group {
            margin-bottom: var(--spacing-sm);
        }

        .input-group label {
            display: block;
            margin-bottom: var(--spacing-xs);
            font-size: 0.9rem;
            color: var(--color-text-primary);
            font-weight: 500;
        }

        .input-group input,
        .input-group textarea,
        .input-group select {
            width: 100%;
            padding: var(--spacing-xs) var(--spacing-sm);
            border: 1px solid var(--color-border);
            border-radius: var(--radius-small);
            font-size: 0.9rem;
            background-color: rgba(255, 255, 255, 0.8);
            transition: all var(--transition-normal) ease;
        }

        /* 输入框聚焦效果 */
        .input-group input:focus,
        .input-group textarea:focus,
        .input-group select:focus {
            outline: none;
            border-color: var(--color-accent);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            transform: translateY(-1px);
            background-color: rgba(255, 255, 255, 0.95);
        }

        /* 统计卡片样式 */
        .stat-card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid var(--color-border);
            border-radius: var(--radius-medium);
            padding: var(--spacing-md);
            box-shadow: var(--shadow-default);
            transition: all var(--transition-normal) ease;
            position: relative;
            overflow: hidden;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
        }

        .stat-card h3 {
            font-size: 0.9rem;
            color: var(--color-text-secondary);
            margin-bottom: var(--spacing-xs);
            font-weight: 500;
        }

        .stat-card .value {
            font-size: 1.75rem;
            font-weight: 700;
            color: var(--color-text-primary);
            margin-bottom: var(--spacing-sm);
        }

        .stat-card .trend {
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: var(--spacing-xs);
        }

        .stat-card .trend.up {
            color: var(--color-success);
        }

        .stat-card .trend.down {
            color: var(--color-danger);
        }

        /* 表格样式 */
        .table-responsive {
            overflow-x: auto;
            border-radius: var(--radius-medium);
            box-shadow: var(--shadow-default);
            background-color: rgba(255, 255, 255, 0.9);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        th {
            background-color: var(--color-light);
            text-align: left;
            padding: var(--spacing-sm);
            font-weight: 600;
            color: var(--color-text-primary);
            border-bottom: 1px solid var(--color-border);
            position: sticky;
            top: 0;
            z-index: 5;
        }

        td {
            padding: var(--spacing-sm);
            border-bottom: 1px solid var(--color-border);
            color: var(--color-text-primary);
            transition: background-color var(--transition-fast) ease;
        }

        tr:hover td {
            background-color: var(--color-hover);
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: var(--spacing-lg);
            flex-wrap: wrap;
            gap: var(--spacing-xs);
        }

        .pagination .page-btn {
            padding: var(--spacing-xs) var(--spacing-sm);
            border: 1px solid var(--color-border);
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: var(--radius-small);
            cursor: pointer;
            transition: all var(--transition-normal) ease;
            color: var(--color-text-primary);
        }

        .pagination .page-btn:hover:not(:disabled) {
            background-color: var(--color-hover);
            transform: translateY(-1px);
            border-color: var(--color-accent);
        }

        .pagination .page-btn.active {
            background-color: var(--color-accent);
            color: white;
            border-color: var(--color-accent);
            box-shadow: var(--shadow-default);
        }

        .pagination .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .pagination .pagination-ellipsis {
            padding: var(--spacing-xs) var(--spacing-sm);
            color: var(--color-text-secondary);
            cursor: default;
        }

        /* 上传区域样式 */
        .upload-area {
            border: 2px dashed var(--color-border);
            border-radius: var(--radius-medium);
            padding: var(--spacing-xl);
            text-align: center;
            cursor: pointer;
            transition: all var(--transition-normal) ease;
            background-color: rgba(59, 130, 246, 0.02);
        }

        .upload-area:hover {
            border-color: var(--color-accent);
            background-color: var(--color-hover);
            transform: translateY(-1px);
            box-shadow: var(--shadow-default);
        }

        .upload-area.dragover {
            border-color: var(--color-success);
            background-color: rgba(16, 185, 129, 0.05);
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
        }

        /* 徽章样式 */
        .badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            transition: all var(--transition-normal) ease;
        }

        .badge-success {
            background-color: rgba(16, 185, 129, 0.1);
            color: var(--color-success);
        }

        .badge-danger {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--color-danger);
        }

        .badge-warning {
            background-color: rgba(245, 158, 11, 0.1);
            color: var(--color-warning);
        }

        .badge-info {
            background-color: rgba(59, 130, 246, 0.1);
            color: var(--color-info);
        }

        /* 下拉筛选样式 */
        .filter-group {
            display: flex;
            gap: var(--spacing-md);
            margin-bottom: var(--spacing-md);
            flex-wrap: wrap;
            background-color: rgba(255, 255, 255, 0.8);
            padding: var(--spacing-md);
            border-radius: var(--radius-medium);
            box-shadow: var(--shadow-default);
        }

        .filter-group .filter-item {
            min-width: 150px;
            flex: 1;
        }

        /* 标签样式 - 圆形色块，选中状态带发光效果 */
        .tag {
            background-color: var(--color-main);
            color: var(--color-text-accent);
            padding: 4px 10px;
            border-radius: var(--radius-small);
            font-size: 0.8rem;
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-xs);
            transition: all var(--transition-normal) ease;
            border: 1px solid transparent;
            cursor: pointer;
            user-select: none;
        }

        .tag:hover {
            background-color: var(--color-hover);
            transform: translateY(-1px);
            box-shadow: var(--shadow-default);
        }

        .tag.selected {
            border-color: var(--color-accent);
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
            transform: translateY(-1px);
        }

        /* 标签容器 */
        .tag-container {
            display: flex;
            flex-wrap: wrap;
            gap: var(--spacing-sm);
            margin-top: var(--spacing-sm);
        }

        /* 统计卡片样式 */
        .stats-card {
            display: flex;
            align-items: center;
            padding: 1.5rem;
            gap: 1rem;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }

        .stats-icon {
            font-size: 2.5rem;
            width: 3.5rem;
            height: 3.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(var(--primary-color), 0.1);
            border-radius: 8px;
            flex-shrink: 0;
        }

        .stats-content {
            flex: 1;
        }

        .stats-number {
            font-size: clamp(1.5rem, 3vw, 2rem);
            font-weight: 600;
            color: var(--text-primary);
            line-height: 1.2;
        }

        .stats-label {
            font-size: 0.875rem;
            color: var(--text-secondary);
            margin-top: 0.25rem;
        }

        /* 图表图例样式 */
        .chart-legend {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .legend-name {
            font-size: 0.875rem;
            color: var(--text-primary);
        }

        .legend-value {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        /* 图表容器 */
        .chart-container {
            height: 300px;
            margin-top: var(--spacing-md);
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: var(--radius-medium);
            padding: var(--spacing-md);
            box-shadow: var(--shadow-default);
            transition: all var(--transition-normal) ease;
            position: relative;
        }

        .chart-container:hover {
            box-shadow: var(--shadow-hover);
            transform: translateY(-1px);
        }

        /* 工具提示 */
        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 120px;
            background-color: var(--color-text-primary);
            color: white;
            text-align: center;
            border-radius: var(--radius-small);
            padding: var(--spacing-xs);
            position: absolute;
            z-index: 100;
            bottom: 125%;
            left: 50%;
            margin-left: -60px;
            opacity: 0;
            transition: opacity var(--transition-normal), transform var(--transition-normal);
            font-size: 0.8rem;
            transform: translateY(5px);
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
            transform: translateY(0);
        }

        /* 分隔线 */
        .divider {
            height: 1px;
            background-color: var(--color-border);
            margin: var(--spacing-lg) 0;
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: var(--spacing-xl);
            color: var(--color-text-secondary);
            font-style: italic;
            background-color: rgba(255, 255, 255, 0.6);
            border-radius: var(--radius-medium);
        }

        /* 隐藏元素 */
        .hidden {
            display: none !important;
        }

        /* 确认对话框样式 */
        .confirm-dialog-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(2px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all var(--transition-normal) ease;
        }

        .confirm-dialog-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .confirm-dialog {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: var(--radius-medium);
            box-shadow: var(--shadow-active);
            padding: var(--spacing-xl);
            max-width: 400px;
            width: 90%;
            transform: scale(0.9) translateY(20px);
            transition: all var(--transition-normal) ease;
            border: 1px solid var(--color-border);
            backdrop-filter: blur(20px);
        }

        .confirm-dialog-overlay.active .confirm-dialog {
            transform: scale(1) translateY(0);
        }

        .confirm-dialog-header {
            margin-bottom: var(--spacing-md);
            text-align: center;
        }

        .confirm-dialog-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--color-text-primary);
            margin-bottom: var(--spacing-xs);
        }

        .confirm-dialog-message {
            color: var(--color-text-secondary);
            font-size: 0.95rem;
            line-height: 1.5;
        }

        .confirm-dialog-actions {
            display: flex;
            gap: var(--spacing-md);
            justify-content: flex-end;
            margin-top: var(--spacing-lg);
        }

        /* 表单样式增强 */
        .form-section {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid var(--color-border);
            border-radius: var(--radius-medium);
            padding: var(--spacing-lg);
            margin-bottom: var(--spacing-lg);
            box-shadow: var(--shadow-default);
            transition: all var(--transition-normal) ease;
        }

        .form-section:hover {
            box-shadow: var(--shadow-hover);
            transform: translateY(-1px);
        }

        .form-row {
            display: flex;
            gap: var(--spacing-md);
            margin-bottom: var(--spacing-sm);
            flex-wrap: wrap;
        }

        .form-row .input-group {
            flex: 1;
            min-width: 200px;
            margin-bottom: var(--spacing-sm);
        }

        /* 输入框验证状态 */
        .input-group input.error,
        .input-group textarea.error,
        .input-group select.error {
            border-color: var(--color-danger);
            background-color: rgba(239, 68, 68, 0.02);
        }

        .input-group input.success,
        .input-group textarea.success,
        .input-group select.success {
            border-color: var(--color-success);
            background-color: rgba(16, 185, 129, 0.02);
        }

        .input-error {
            color: var(--color-danger);
            font-size: 0.8rem;
            margin-top: 4px;
            display: block;
        }

        /* 操作区域样式 */
        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-lg);
            background-color: rgba(255, 255, 255, 0.8);
            padding: var(--spacing-md);
            border-radius: var(--radius-medium);
            box-shadow: var(--shadow-default);
            flex-wrap: wrap;
            gap: var(--spacing-md);
        }

        .action-bar-left,
        .action-bar-right {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
            flex-wrap: wrap;
        }

        /* 操作按钮组 */
        .btn-group {
            display: flex;
            gap: var(--spacing-xs);
            align-items: center;
        }

        /* 导入导出样式 */
        .import-export-group {
            display: flex;
            gap: var(--spacing-sm);
            align-items: center;
        }

        .import-export-group .btn {
            white-space: nowrap;
        }

        /* 表格操作列样式 */
        .table-actions {
            display: flex;
            gap: var(--spacing-xs);
            align-items: center;
        }

        .table-actions .btn {
            padding: 4px 8px;
            font-size: 0.8rem;
        }

        /* 批量操作样式 */
        .batch-actions {
            display: flex;
            gap: var(--spacing-sm);
            margin-bottom: var(--spacing-md);
            align-items: center;
        }

        /* 数据详情卡片 */
        .detail-card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid var(--color-border);
            border-radius: var(--radius-medium);
            padding: var(--spacing-lg);
            box-shadow: var(--shadow-default);
            margin-bottom: var(--spacing-lg);
        }

        .detail-row {
            display: flex;
            margin-bottom: var(--spacing-sm);
            padding-bottom: var(--spacing-sm);
            border-bottom: 1px solid var(--color-mid);
        }

        .detail-row:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .detail-label {
            font-weight: 500;
            color: var(--color-text-secondary);
            min-width: 120px;
            flex-shrink: 0;
        }

        .detail-value {
            color: var(--color-text-primary);
            flex: 1;
            word-break: break-word;
        }

        /* 状态指示器 */
        .status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }

        .status-dot.active {
            background-color: var(--color-success);
        }

        .status-dot.inactive {
            background-color: var(--color-text-light);
            animation: none;
        }

        /* 动画增强 */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .slide-in {
            animation: slideIn 0.4s ease-out;
        }

        /* 加载动画 - 微妙动画：通知点脉冲效果 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
            font-size: 1.1rem;
            color: var(--color-text-secondary);
        }

        .loading::after {
            content: '';
            width: 20px;
            height: 20px;
            margin-left: 10px;
            border: 2px solid var(--color-light);
            border-top: 2px solid var(--color-accent);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        /* 通知点 - 脉冲效果 */
        .notification-dot {
            position: absolute;
            top: -5px;
            right: -5px;
            width: 12px;
            height: 12px;
            background-color: var(--color-danger);
            border-radius: 50%;
            animation: pulse 2s infinite;
        }

        /* 元素悬浮动画 - 上下4px浮动 */
        .float {
            animation: float 3s ease-in-out infinite;
        }

        /* 动画定义 */
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
                opacity: 1;
            }
            50% {
                transform: scale(1.05);
                opacity: 0.8;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }

        @keyframes float {
            0% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-4px);
            }
            100% {
                transform: translateY(0);
            }
        }

        /* 响应式设计 - 多级适配 */
        @media (max-width: 1200px) {
            .grid-cols-4 {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 992px) {
            .grid-cols-3 {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .container {
                padding: var(--spacing-md);
            }
            
            .grid-cols-2, .grid-cols-3, .grid-cols-4 {
                grid-template-columns: 1fr;
            }

            .filter-group {
                flex-direction: column;
            }

            .filter-group .filter-item {
                width: 100%;
            }

            .page-title {
                font-size: 1.5rem;
            }

            .tabs {
                flex-wrap: nowrap;
                overflow-x: auto;
                padding-bottom: var(--spacing-sm);
            }
            
            .tab {
                font-size: 0.9rem;
                padding: var(--spacing-xs) var(--spacing-md);
            }
            
            .card {
                padding: var(--spacing-md);
            }
            
            .stat-card .value {
                font-size: 1.5rem;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: var(--spacing-sm);
            }
            
            .card {
                padding: var(--spacing-sm);
            }
            
            .btn {
                padding: var(--spacing-xs) var(--spacing-sm);
                font-size: 0.85rem;
            }
        }

        /* 网格布局 */
        .grid {
            display: grid;
            gap: var(--spacing-lg);
        }

        .grid-cols-2 {
            grid-template-columns: repeat(2, 1fr);
        }

        .grid-cols-3 {
            grid-template-columns: repeat(3, 1fr);
        }

        .grid-cols-4 {
            grid-template-columns: repeat(4, 1fr);
        }

        /* 切换按钮组 */
        .toggle-group {
            display: flex;
            gap: var(--spacing-sm);
            margin-bottom: var(--spacing-md);
            flex-wrap: wrap;
        }

        .toggle-group label {
            cursor: pointer;
            transition: transform var(--transition-fast) ease;
            user-select: none;
        }

        .toggle-group label:hover {
            transform: translateY(-1px);
        }

        /* 全局过渡动画 */
        a,
        button,
        select,
        input,
        textarea,
        .tab,
        .stat-card,
        .tag,
        .chart-container,
        .btn {
            transition: all var(--transition-normal) ease;
        }

        /* 防止点击时的蓝色高亮 */
        * {
            -webkit-tap-highlight-color: transparent;
        }
        
        .input-group input:focus,
        .input-group textarea:focus,
        .input-group select:focus {
            outline: none;
            border-color: var(--color-accent);
            box-shadow: 0 0 0 2px var(--color-hover);
        }

        /* 网格布局 */
        .grid {
            display: grid;
            gap: var(--spacing-md);
        }

        .grid-cols-1 {
            grid-template-columns: 1fr;
        }

        .grid-cols-2 {
            grid-template-columns: repeat(2, 1fr);
        }

        .grid-cols-3 {
            grid-template-columns: repeat(3, 1fr);
        }

        /* 统计卡片样式 */
        .stat-card {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            padding: var(--spacing-md);
            background-color: var(--color-main);
            border-radius: var(--radius-medium);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 600;
            color: var(--color-text-accent);
            margin-bottom: var(--spacing-xs);
        }

        .stat-label {
            font-size: 0.9rem;
            color: var(--color-text-secondary);
        }

        /* 表格样式 */
        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: var(--spacing-sm);
        }

        .table th,
        .table td {
            padding: var(--spacing-xs) var(--spacing-sm);
            text-align: left;
            border-bottom: 1px solid var(--color-mid);
        }

        .table th {
            background-color: var(--color-mid);
            font-weight: 500;
            color: var(--color-text-primary);
        }

        .table tr:hover {
            background-color: var(--color-hover);
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            gap: var(--spacing-xs);
            margin-top: var(--spacing-md);
        }

        .page-btn {
            padding: var(--spacing-xs);
            border: 1px solid var(--color-border);
            background-color: white;
            cursor: pointer;
            border-radius: var(--radius-small);
            transition: all 0.3s ease;
        }

        .page-btn:hover {
            background-color: var(--color-hover);
        }

        .page-btn.active {
            background-color: var(--color-accent);
            color: white;
            border-color: var(--color-accent);
        }

        /* 上传区域样式 */
        .upload-area {
            border: 2px dashed var(--color-border);
            border-radius: var(--radius-medium);
            padding: var(--spacing-xl);
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background-color: rgba(255, 255, 255, 0.5);
        }

        .upload-area:hover {
            border-color: var(--color-accent);
            background-color: var(--color-hover);
        }

        .upload-area input[type="file"] {
            display: none;
        }

        /* 徽章样式 */
        .badge {
            display: inline-block;
            padding: 0.2rem 0.6rem;
            border-radius: var(--radius-circle);
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-success {
            background-color: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }

        .badge-warning {
            background-color: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
        }

        .badge-danger {
            background-color: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        /* 下拉筛选样式 */
        .filter-group {
            display: flex;
            gap: var(--spacing-sm);
            flex-wrap: wrap;
            margin-bottom: var(--spacing-md);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .grid-cols-2,
            .grid-cols-3 {
                grid-template-columns: 1fr;
            }

            .filter-group {
                flex-direction: column;
            }

            .tabs {
                overflow-x: auto;
                white-space: nowrap;
            }
        }

        /* 加载动画 */
        .loader {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid var(--color-mid);
            border-radius: var(--radius-circle);
            border-top-color: var(--color-accent);
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 工具提示 */
        .tooltip {
            position: relative;
            cursor: help;
        }

        .tooltip::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background-color: var(--color-text-primary);
            color: white;
            padding: 0.3rem 0.6rem;
            border-radius: var(--radius-small);
            font-size: 0.8rem;
            white-space: nowrap;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
            margin-bottom: 0.5rem;
        }

        .tooltip:hover::after {
            opacity: 1;
        }

        /* 分隔线 */
        .divider {
            height: 1px;
            background-color: var(--color-border);
            margin: var(--spacing-md) 0;
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: var(--spacing-xl);
            color: var(--color-text-secondary);
        }

        /* 动画效果 */
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
    <!-- 通知容器 -->
    <div id="toastContainer" class="toast-container"></div>
    
    <!-- 加载覆盖层 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner"></div>
        <div class="loading-text" id="loadingText">加载中...</div>
    </div>
    
    <!-- 确认对话框 -->
    <div id="confirm-dialog" class="confirm-dialog-overlay">
        <div class="confirm-dialog">
            <div class="confirm-dialog-header">
                <h3 class="confirm-dialog-title" id="confirm-title">确认操作</h3>
                <p class="confirm-dialog-message" id="confirm-message">您确定要执行此操作吗？</p>
            </div>
            <div class="confirm-dialog-actions">
                <button id="confirm-cancel" class="btn btn-outline">取消</button>
                <button id="confirm-ok" class="btn btn-primary">确定</button>
            </div>
        </div>
    </div>
    
    <div id="header" style="margin: 20px 20px 0 20px; padding: 20px 25px; background-color: rgba(255, 255, 255, 0.92); backdrop-filter: blur(20px); border-radius: var(--radius-medium); border: 1px solid var(--color-border); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02); background-image: linear-gradient(135deg, rgba(59, 130, 246, 0.03), transparent);">
        <h1 style="font-size: clamp(1.5rem, 3vw, 2rem); font-weight: 700; color: var(--text-primary); margin: 0; letter-spacing: -0.5px; background: linear-gradient(135deg, var(--text-primary), #475569); -webkit-background-clip: text; background-clip: text; display: inline;">智能数据引擎</h1>
    </div>
    
    <div id="main-container" style="background-color: white; margin: 20px; padding: 20px; width: calc(100% - 40px); min-height: calc(100vh - 120px); box-shadow: var(--shadow-default); border-radius: var(--radius-medium); box-sizing: border-box;">

        <!-- 标签页导航 -->
        <div class="tabs" id="tabs-container">
            <button class="tab active" data-tab="data-analysis">数据关联分析</button>
            <button class="tab" data-tab="file-trace">文件溯源分析</button>
            <button class="tab" data-tab="file-fingerprint">文件指纹库</button>
            <button class="tab" data-tab="word-segment">分词词库管理</button>
            <button class="tab" data-tab="user-segment">用户分群分析</button>
        </div>

        <!-- 数据关联分析标签页内容 -->
        <div id="data-analysis" class="tab-content active">
            <!-- 数据中心统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
                <div class="stat-card">
                    <div class="stat-number" id="total-alerts">0</div>
                    <div class="stat-label">全部风险告警</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="focus-alerts">0</div>
                    <div class="stat-label">关注数据中心告警</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="alert-trend">0%</div>
                    <div class="stat-label">告警趋势变化</div>
                </div>
            </div>

            <!-- 数据中心告警排名 -->
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">数据中心告警排名</h2>
                    <div class="filter-group">
                        <select id="alert-time-filter">
                            <option value="24h">最近24小时</option>
                            <option value="7d" selected>最近7天</option>
                            <option value="30d">最近30天</option>
                        </select>
                    </div>
                </div>
                <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>数据中心</th>
                            <th>告警数量</th>
                            <th>严重程度</th>
                            <th>趋势</th>
                        </tr>
                    </thead>
                    <tbody id="alert-ranking-table">
                        <tr>
                            <td colspan="5" class="empty-state">暂无数据</td>
                        </tr>
                    </tbody>
                </table>
                </div>
            </div>
        </div>

        <!-- 文件溯源分析标签页内容 -->
        <div id="file-trace" class="tab-content">
            <!-- 敏感文件分析卡片 -->
            <div class="card mb-6">
                <div class="card-header">
                    <h2 class="card-title">敏感文件分析</h2>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div class="stat-item">
                        <div class="stat-number" id="sensitive-file-count">0</div>
                        <div class="stat-label">敏感文件总数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="high-risk-files">0</div>
                        <div class="stat-label">高风险文件</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="sensitive-types">0</div>
                        <div class="stat-label">敏感类型</div>
                    </div>
                </div>
                <div class="flex gap-4">
                    <button id="analyze-sensitive-files-btn" class="btn btn-primary">开始敏感文件扫描</button>
                    <button id="view-sensitive-files-btn" class="btn btn-outline">查看敏感文件列表</button>
                </div>
            </div>
            
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- 文件溯源方式选择 -->
                <div class="card lg:col-span-1">
                    <div class="card-header">
                        <h2 class="card-title">溯源方式</h2>
                    </div>
                    <div class="input-group">
                        <label>
                            <input type="radio" name="trace-method" value="file-upload" checked>
                            导入文件
                        </label>
                    </div>
                    <div class="input-group">
                        <label>
                            <input type="radio" name="trace-method" value="content-fragment">
                            文件内容片段
                        </label>
                    </div>
                    <div class="input-group">
                        <label>
                            <input type="radio" name="trace-method" value="word-segment">
                            文件内容分词
                        </label>
                    </div>

                    <!-- 文件上传区域 -->
                    <div id="file-upload-area" class="upload-area">
                        <input type="file" id="file-upload" multiple accept=".doc,.docx,.xls,.xlsx,.pdf">
                        <div>
                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                                <polyline points="7 10 12 15 17 10"></polyline>
                                <line x1="12" y1="15" x2="12" y2="3"></line>
                            </svg>
                            <p>点击或拖拽文件至此处上传</p>
                            <p class="text-xs text-secondary">支持格式：doc, docx, xls, xlsx, pdf</p>
                        </div>
                    </div>

                    <!-- 文件内容片段输入 -->
                    <div id="content-fragment-area" class="input-group" style="display: none;">
                        <label for="content-fragment">文件内容片段</label>
                        <textarea id="content-fragment" rows="6" placeholder="请输入文件内容片段..."></textarea>
                    </div>

                    <!-- 文件内容分词输入 -->
                    <div id="word-segment-area" class="input-group" style="display: none;">
                        <label for="word-segment-input">文件内容分词</label>
                        <textarea id="word-segment-input" rows="6" placeholder="请输入文件内容分词，用逗号分隔..."></textarea>
                    </div>

                    <!-- 溯源类型选择 -->
                    <div class="input-group">
                        <label>溯源类型</label>
                        <select id="trace-type">
                            <option value="tag" selected>标签溯源</option>
                            <option value="content">内容溯源</option>
                        </select>
                    </div>

                    <button id="start-trace-btn" class="btn btn-primary" style="width: 100%;">开始溯源分析</button>
                </div>

                <!-- 历史溯源任务 -->
                <div class="card lg:col-span-2">
                    <div class="card-header">
                        <h2 class="card-title">历史溯源任务</h2>
                        <div class="filter-group">
                            <select id="task-time-filter">
                                <option value="all">全部时间</option>
                                <option value="today">今天</option>
                                <option value="7d">最近7天</option>
                            </select>
                            <select id="task-method-filter">
                                <option value="all">全部方式</option>
                                <option value="file-upload">导入文件</option>
                                <option value="content-fragment">内容片段</option>
                                <option value="word-segment">内容分词</option>
                            </select>
                            <select id="task-type-filter">
                                <option value="all">全部类型</option>
                                <option value="tag">标签溯源</option>
                                <option value="content">内容溯源</option>
                            </select>
                        </div>
                    </div>
                    <table class="table">
                        <thead>
                            <tr>
                                <th>任务ID</th>
                                <th>溯源方式</th>
                                <th>溯源类型</th>
                                <th>时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="trace-tasks-table">
                            <tr>
                                <td colspan="6" class="empty-state">暂无历史任务</td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="pagination">
                        <button class="page-btn">上一页</button>
                        <button class="page-btn active">1</button>
                        <button class="page-btn">下一页</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 文件指纹库标签页内容 -->
        <div id="file-fingerprint" class="tab-content">
            <!-- 添加文件指纹表单 -->
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">添加文件指纹</h2>
                </div>
                <div class="card-body">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-md">
                        <div class="input-group">
                            <label for="fingerprint-filename">文件名称</label>
                            <input type="text" id="fingerprint-filename" placeholder="请输入文件名称">
                        </div>
                        <div class="input-group">
                            <label for="fingerprint-hash">文件指纹</label>
                            <input type="text" id="fingerprint-hash" placeholder="请输入文件指纹(Minhash值)">
                        </div>
                        <div class="input-group">
                            <label for="fingerprint-type">文件类型</label>
                            <select id="fingerprint-type">
                                <option value="doc">文档</option>
                                <option value="pdf">PDF</option>
                                <option value="excel">Excel</option>
                                <option value="image">图片</option>
                                <option value="other">其他</option>
                            </select>
                        </div>
                    </div>
                    <button id="add-fingerprint-btn" class="btn btn-primary mt-md">添加文件指纹</button>
                </div>
            </div>

            <!-- 文件指纹查询 -->
            <div class="card mt-md">
                <div class="card-header">
                    <h2 class="card-title">文件指纹查询</h2>
                    <div class="filter-group">
                        <input type="text" id="fingerprint-search" placeholder="输入文件指纹或关键词">
                        <button id="search-fingerprint-btn" class="btn btn-primary">查询</button>
                    </div>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>文件名称</th>
                            <th>文件指纹</th>
                            <th>文件类型</th>
                            <th>创建时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="fingerprint-table">
                        <tr>
                            <td colspan="6" class="empty-state">暂无文件指纹数据</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 分词词库管理标签页内容 -->
        <div id="word-segment" class="tab-content">
            <!-- 添加词语表单 -->
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">添加词语</h2>
                </div>
                <div class="card-body">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-md">
                        <div class="input-group">
                            <label for="word-input">词语</label>
                            <input type="text" id="word-input" placeholder="请输入要添加的词语">
                        </div>
                        <div class="input-group">
                            <label for="word-category">分类</label>
                            <select id="word-category">
                                <option value="default">默认分类</option>
                                <option value="sensitive">敏感词</option>
                                <option value="technical">技术术语</option>
                                <option value="custom">自定义</option>
                            </select>
                        </div>
                        <div class="input-group">
                            <label for="word-weight">权重</label>
                            <input type="number" id="word-weight" value="1" min="1" max="10">
                        </div>
                    </div>
                    <button id="add-word-btn" class="btn btn-primary mt-md">添加词语</button>
                </div>
            </div>

            <!-- 批量导入导出 -->
            <div class="card mt-md">
                <div class="card-header">
                    <h2 class="card-title">批量导入导出</h2>
                </div>
                <div class="card-body">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-md">
                        <!-- 导入词语 -->
                        <div>
                            <h3 class="subtitle">导入词语</h3>
                            <div class="input-group">
                                <label for="words-import-text">输入词语（每行一个）</label>
                                <textarea id="words-import-text" rows="6" placeholder="请输入要导入的词语，每行一个..."></textarea>
                            </div>
                            <div class="input-group">
                                <label for="import-category">导入分类</label>
                                <select id="import-category">
                                    <option value="default">默认分类</option>
                                    <option value="sensitive">敏感词</option>
                                    <option value="technical">技术术语</option>
                                    <option value="custom">自定义</option>
                                </select>
                            </div>
                            <button id="import-words-btn" class="btn btn-primary mt-md">导入词语</button>
                        </div>

                        <!-- 导出词语 -->
                        <div>
                            <h3 class="subtitle">导出词语</h3>
                            <div class="input-group">
                                <label for="export-category">导出分类</label>
                                <select id="export-category">
                                    <option value="all">全部</option>
                                    <option value="default">默认分类</option>
                                    <option value="sensitive">敏感词</option>
                                    <option value="technical">技术术语</option>
                                    <option value="custom">自定义</option>
                                </select>
                            </div>
                            <button id="export-words-btn" class="btn btn-primary mt-md">导出词语</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 词语搜索 -->
            <div class="card mt-md">
                <div class="card-header">
                    <h2 class="card-title">分词词库查询</h2>
                    <div class="filter-group">
                        <input type="text" id="word-search" placeholder="搜索词语">
                        <select id="word-search-category">
                            <option value="all">全部分类</option>
                            <option value="default">默认分类</option>
                            <option value="sensitive">敏感词</option>
                            <option value="technical">技术术语</option>
                            <option value="custom">自定义</option>
                        </select>
                        <button id="search-word-btn" class="btn btn-primary">搜索</button>
                    </div>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>词语</th>
                            <th>分类</th>
                            <th>权重</th>
                            <th>添加时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="word-library-table">
                        <tr>
                            <td colspan="5" class="empty-state">暂无词语数据</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 用户分群分析标签页内容 -->
        <div id="user-segment" class="tab-content">
            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                <div class="card stats-card">
                    <div class="stats-icon">👥</div>
                    <div class="stats-content">
                        <div class="stats-number" id="total-users">--</div>
                        <div class="stats-label">总用户数</div>
                    </div>
                </div>
                <div class="card stats-card">
                    <div class="stats-icon">🏷️</div>
                    <div class="stats-content">
                        <div class="stats-number" id="total-tags">--</div>
                        <div class="stats-label">分群标签数</div>
                    </div>
                </div>
                <div class="card stats-card">
                    <div class="stats-icon">⚠️</div>
                    <div class="stats-content">
                        <div class="stats-number" id="high-risk-users">--</div>
                        <div class="stats-label">高风险用户</div>
                    </div>
                </div>
                <div class="card stats-card">
                    <div class="stats-icon">📈</div>
                    <div class="stats-content">
                        <div class="stats-number" id="risk-trend">--</div>
                        <div class="stats-label">风险趋势</div>
                    </div>
                </div>
            </div>

            <!-- 图表区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
                <!-- 用户分群分布图 -->
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">用户分群分布</h2>
                    </div>
                    <div class="card-body">
                        <div id="segment-distribution-chart" class="chart-container"></div>
                    </div>
                </div>

                <!-- 用户行为趋势图 -->
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">用户行为趋势</h2>
                        <div class="filter-group">
                            <select id="trend-time-filter">
                                <option value="6m">最近6个月</option>
                                <option value="3m">最近3个月</option>
                                <option value="1m">最近1个月</option>
                            </select>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="user-behavior-trend" class="chart-container"></div>
                    </div>
                </div>
            </div>

            <!-- 标签关联网络和分群标签管理 -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
                <!-- 标签关联网络图 -->
                <div class="card lg:col-span-1">
                    <div class="card-header">
                        <h2 class="card-title">标签关联网络</h2>
                    </div>
                    <div class="card-body">
                        <div id="tag-relationship-network" class="chart-container"></div>
                    </div>
                </div>

                <!-- 分群标签管理 -->
                <div class="card lg:col-span-2">
                    <div class="card-header">
                        <h2 class="card-title">分群标签管理</h2>
                        <div class="filter-group">
                            <input type="text" id="segment-tag-search" placeholder="搜索标签">
                            <button id="search-segment-tag-btn" class="btn btn-primary">搜索</button>
                            <button id="add-segment-tag-btn" class="btn btn-primary">添加标签</button>
                        </div>
                    </div>
                    <table class="table">
                        <thead>
                            <tr>
                                <th>颜色</th>
                                <th>标签名称</th>
                                <th>描述</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="segment-tags-table">
                            <tr>
                                <td colspan="5" class="empty-state">暂无分群标签数据</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 分群规则管理 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h2 class="card-title">分群规则管理</h2>
                    <div class="filter-group">
                        <input type="text" id="segment-rule-search" placeholder="搜索规则名称">
                        <button id="search-segment-rule-btn" class="btn btn-primary">搜索</button>
                        <button id="add-segment-rule-btn" class="btn btn-primary">添加规则</button>
                    </div>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>规则名称</th>
                            <th>规则描述</th>
                            <th>规则条件</th>
                            <th>创建时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="segment-rules-table">
                        <tr>
                            <td colspan="5" class="empty-state">暂无分群规则数据</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 全局DOM缓存对象
        const domCache = {};
        
        // 预缓存常用DOM元素
        function preCacheElements() {
            const commonElements = [
                'toastContainer', 'loadingOverlay', 'loadingText', 'confirm-dialog',
                'confirm-title', 'confirm-message', 'confirm-ok', 'confirm-cancel',
                'file-upload-area', 'content-fragment-area', 'word-segment-area',
                'total-alerts', 'focus-alerts', 'alert-trend', 'alert-time-filter',
                'alert-ranking-table', 'trace-type', 'file-upload', 'content-fragment',
                'word-segment-input', 'start-trace-btn', 'trace-tasks-table',
                'task-time-filter', 'task-method-filter', 'task-type-filter',
                'add-fingerprint-btn', 'search-fingerprint-btn', 'fingerprint-filename',
                'fingerprint-hash', 'fingerprint-type', 'fingerprint-table',
                'add-word-btn', 'import-words-btn', 'export-words-btn', 'search-word-btn',
                'word-input', 'word-category', 'word-weight', 'words-import-text',
                'import-category', 'export-category', 'word-search', 'word-search-category',
                'word-library-table', 'add-segment-tag-btn', 'search-segment-tag-btn',
                'segment-tag-name', 'segment-tag-description', 'segment-tag-color',
                'segment-tag-search', 'segment-tags-table', 'trend-time-filter',
                'total-users', 'total-tags', 'high-risk-users', 'risk-trend',
                'segment-distribution-chart', 'tag-relationship-network',
                'user-behavior-trend', 'add-segment-rule-btn', 'segment-rule-search',
                'segment-rule-name', 'segment-rule-conditions', 'segment-rule-description',
                'save-segment-rule-btn', 'cancel-edit-btn', 'segment-rules-table'
            ];
            
            commonElements.forEach(function(id) {
                getElement(id);
            });
        };
        
        // 初始化时执行预缓存
        document.addEventListener('DOMContentLoaded', preCacheElements);
        
        // 获取并缓存DOM元素
        function getElement(id) {
            if (!domCache[id]) {
                domCache[id] = document.getElementById(id);
            }
            return domCache[id];
        }
        
        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function executedFunction() {
                const args = arguments;
                const later = function() {
                    clearTimeout(timeout);
                    func.apply(null, args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
        
        // 初始化数据
        document.addEventListener('DOMContentLoaded', function() {
            // 预缓存常用DOM元素
            const commonElements = ['tabs-container', 'alert-time-filter', 'task-time-filter', 'fingerprint-search', 'segment-tag-search', 'segment-rule-search'];
            commonElements.forEach(function(id) {
                getElement(id);
            });
            
            // 初始化标签页切换
            initTabs();
            
            // 初始化溯源方式切换
            initTraceMethods();
            
            // 初始化模拟数据 - 添加防抖处理
            setTimeout(initMockData, 100); // 延迟执行，避免阻塞渲染
        });

        // 初始化标签页切换（使用事件委托优化性能）
        function initTabs() {
            const tabsContainer = getElement('tabs-container');
            
            if (tabsContainer) {
                // 使用事件委托处理点击事件
                tabsContainer.addEventListener('click', function(event) {
                    const tab = event.target.closest('.tab');
                    if (!tab) return;
                    
                    // 移除所有激活状态（只在需要时操作DOM）
                    const activeTab = this.querySelector('.tab.active');
                    if (activeTab && activeTab !== tab) {
                        activeTab.classList.remove('active');
                    }
                    
                    // 添加当前激活状态
                    tab.classList.add('active');
                    
                    // 更新内容显示
                    const targetId = tab.dataset.tab;
                    const activeContent = document.querySelector('.tab-content.active');
                    if (activeContent) {
                        activeContent.classList.remove('active');
                    }
                    
                    const targetContent = getElement(targetId);
                    if (targetContent) {
                        targetContent.classList.add('active');
                    }
                });
            }
        }

        // 初始化溯源方式切换
        function initTraceMethods() {
            const traceMethods = document.querySelectorAll('input[name="trace-method"]');
            const fileUploadArea = getElement('file-upload-area');
            const contentFragmentArea = getElement('content-fragment-area');
            const wordSegmentArea = getElement('word-segment-area');
            
            traceMethods.forEach(function(method) {
                method.addEventListener('change', function() {
                    if (fileUploadArea) fileUploadArea.style.display = 'none';
                    if (contentFragmentArea) contentFragmentArea.style.display = 'none';
                    if (wordSegmentArea) wordSegmentArea.style.display = 'none';
                    
                    if (this.value === 'file-upload' && fileUploadArea) {
                        fileUploadArea.style.display = 'block';
                    } else if (this.value === 'content-fragment' && contentFragmentArea) {
                        contentFragmentArea.style.display = 'block';
                    } else if (this.value === 'word-segment' && wordSegmentArea) {
                        wordSegmentArea.style.display = 'block';
                    }
                });
            });
        }

        // 数据中心风险告警分析模块
        function initDataAnalysisModule() {
            // 模拟告警数据
            const mockAlertData = {
                totalAlerts: 1245,
                focusAlerts: 456,
                alertTrend: '+12.5%',
                dataCenters: [
                    { id: 1, name: '华东数据中心', alerts: 234, severity: '高', trend: '+8%', isFocus: true },
                    { id: 2, name: '华北数据中心', alerts: 189, severity: '高', trend: '-3%', isFocus: true },
                    { id: 3, name: '华南数据中心', alerts: 156, severity: '中', trend: '+5%', isFocus: true },
                    { id: 4, name: '西南数据中心', alerts: 123, severity: '中', trend: '+2%', isFocus: false },
                    { id: 5, name: '西北数据中心', alerts: 98, severity: '低', trend: '-1%', isFocus: false },
                    { id: 6, name: '东北数据中心', alerts: 76, severity: '低', trend: '+4%', isFocus: false }
                ]
            };

            // 更新统计卡片数据
            const totalAlertsEl = getElement('total-alerts');
            const focusAlertsEl = getElement('focus-alerts');
            const alertTrendEl = getElement('alert-trend');
            
            if (totalAlertsEl) totalAlertsEl.textContent = mockAlertData.totalAlerts?.toLocaleString() || '0';
            if (focusAlertsEl) focusAlertsEl.textContent = mockAlertData.focusAlerts?.toLocaleString() || '0';
            if (alertTrendEl) alertTrendEl.textContent = mockAlertData.alertTrend || '0%';

            // 渲染告警排名表格
            renderAlertRankingTable(mockAlertData.dataCenters);

            // 绑定时间筛选事件
            const alertTimeFilter = getElement('alert-time-filter');
            if (alertTimeFilter) {
                alertTimeFilter.addEventListener('change', function() {
                    // 根据选择的时间范围更新数据
                    updateAlertDataByTimeRange(this.value);
                });
            }
        }

        // 渲染告警排名表格
        function renderAlertRankingTable(dataCenters) {
            const tableBody = getElement('alert-ranking-table');
            
            if (!tableBody) return;
            
            tableBody.innerHTML = '';

            if (!dataCenters || dataCenters.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="empty-state">暂无数据</td>
                    </tr>
                `;
                return;
            }

            dataCenters.forEach(function(center, index) {
                const trendClass = center.trend?.startsWith('+') ? 'badge-danger' : 'badge-success';
                const severityClass = center.severity === '高' ? 'badge-danger' : 
                                     center.severity === '中' ? 'badge-warning' : 'badge-success';

                const row = document.createElement('tr');
                row.className = center.isFocus ? 'bg-blue-50' : '';
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>
                        ${center.name || '未知数据中心'}
                        ${center.isFocus ? '<span class="badge badge-primary" style="margin-left: 8px;">关注</span>' : ''}
                    </td>
                    <td>${center.alerts || 0}</td>
                    <td><span class="badge ${severityClass}">${center.severity || '低'}</span></td>
                    <td><span class="badge ${trendClass}">${center.trend || '0%'}</span></td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 根据时间范围更新告警数据
        function updateAlertDataByTimeRange(timeRange) {
            let mockData;

            switch(timeRange) {
                case '24h':
                    mockData = {
                        totalAlerts: 189,
                        focusAlerts: 67,
                        alertTrend: '-5.2%',
                        dataCenters: [
                            { id: 1, name: '华东数据中心', alerts: 45, severity: '高', trend: '-2%', isFocus: true },
                            { id: 2, name: '华北数据中心', alerts: 38, severity: '高', trend: '-3%', isFocus: true },
                            { id: 3, name: '华南数据中心', alerts: 29, severity: '中', trend: '+1%', isFocus: true },
                            { id: 4, name: '西南数据中心', alerts: 22, severity: '中', trend: '-1%', isFocus: false },
                            { id: 5, name: '西北数据中心', alerts: 18, severity: '低', trend: '0%', isFocus: false },
                            { id: 6, name: '东北数据中心', alerts: 15, severity: '低', trend: '+2%', isFocus: false }
                        ]
                    };
                    break;
                case '7d':
                    mockData = {
                        totalAlerts: 1245,
                        focusAlerts: 456,
                        alertTrend: '+12.5%',
                        dataCenters: [
                            { id: 1, name: '华东数据中心', alerts: 234, severity: '高', trend: '+8%', isFocus: true },
                            { id: 2, name: '华北数据中心', alerts: 189, severity: '高', trend: '-3%', isFocus: true },
                            { id: 3, name: '华南数据中心', alerts: 156, severity: '中', trend: '+5%', isFocus: true },
                            { id: 4, name: '西南数据中心', alerts: 123, severity: '中', trend: '+2%', isFocus: false },
                            { id: 5, name: '西北数据中心', alerts: 98, severity: '低', trend: '-1%', isFocus: false },
                            { id: 6, name: '东北数据中心', alerts: 76, severity: '低', trend: '+4%', isFocus: false }
                        ]
                    };
                    break;
                case '30d':
                    mockData = {
                        totalAlerts: 5678,
                        focusAlerts: 1890,
                        alertTrend: '+8.3%',
                        dataCenters: [
                            { id: 1, name: '华东数据中心', alerts: 890, severity: '高', trend: '+5%', isFocus: true },
                            { id: 2, name: '华北数据中心', alerts: 765, severity: '高', trend: '+2%', isFocus: true },
                            { id: 3, name: '华南数据中心', alerts: 678, severity: '中', trend: '+7%', isFocus: true },
                            { id: 4, name: '西南数据中心', alerts: 543, severity: '中', trend: '+3%', isFocus: false },
                            { id: 5, name: '西北数据中心', alerts: 432, severity: '低', trend: '+1%', isFocus: false },
                            { id: 6, name: '东北数据中心', alerts: 321, severity: '低', trend: '+4%', isFocus: false }
                        ]
                    };
                    break;
                default:
                    return;
            }

            // 更新界面数据
            const totalAlertsEl = getElement('total-alerts');
            const focusAlertsEl = getElement('focus-alerts');
            const alertTrendEl = getElement('alert-trend');
            
            if (totalAlertsEl) {
                totalAlertsEl.textContent = mockData.totalAlerts ? mockData.totalAlerts.toLocaleString() : '0';
            }
            if (focusAlertsEl) {
                focusAlertsEl.textContent = mockData.focusAlerts ? mockData.focusAlerts.toLocaleString() : '0';
            }
            if (alertTrendEl) {
                alertTrendEl.textContent = mockData.alertTrend || '0%';
            }
            
            if (mockData.dataCenters) {
                renderAlertRankingTable(mockData.dataCenters);
            }
        }



        // 生成敏感文件模拟数据
        function generateMockSensitiveFiles() {
            if (!localStorage.getItem('sensitiveFiles')) {
                const sensitiveFiles = [];
                const fileTypes = ['doc', 'docx', 'xls', 'xlsx', 'pdf'];
                const fileNames = ['财务报表', '客户信息', '项目机密', '技术文档', '员工档案', '合同模板', '审计报告', '会议纪要'];
                const sensitiveTypes = ['个人信息', '商业机密', '财务数据', '技术秘密', '法律文件'];
                const riskLevels = ['低', '中', '高'];
                
                // 生成20个模拟敏感文件
                for (let i = 0; i < 20; i++) {
                    const fileName = fileNames[Math.floor(Math.random() * fileNames.length)];
                    const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)];
                    const sensitiveType = sensitiveTypes[Math.floor(Math.random() * sensitiveTypes.length)];
                    const riskLevel = riskLevels[Math.floor(Math.random() * riskLevels.length)];
                    const date = new Date();
                    date.setDate(date.getDate() - Math.floor(Math.random() * 60)); // 最近60天内的随机日期
                    
                    sensitiveFiles.push({
                        id: `sensitive-file-${i+1}`,
                        filename: `${fileName}_${i+1}.${fileType}`,
                        type: fileType,
                        sensitiveType: sensitiveType,
                        riskLevel: riskLevel,
                        detectedDate: date.toISOString(),
                        status: Math.random() > 0.5 ? '已处理' : '未处理'
                    });
                }
                
                localStorage.setItem('sensitiveFiles', JSON.stringify(sensitiveFiles));
            }
        }
        
        // 初始化敏感文件分析模块
        function initSensitiveFileAnalysis() {
            // 生成模拟数据
            generateMockSensitiveFiles();
            
            // 更新统计数据
            updateSensitiveFileStats();
            
            // 绑定事件监听器
            const analyzeBtn = getElement('analyze-sensitive-files-btn');
            const viewBtn = getElement('view-sensitive-files-btn');
            
            if (analyzeBtn) {
                analyzeBtn.addEventListener('click', function() {
                    // 显示加载状态
                    showLoading('正在进行敏感文件扫描...');
                    
                    // 模拟扫描过程
                    setTimeout(function() {
                        // 随机生成新的敏感文件
                        const newFilesCount = Math.floor(Math.random() * 5) + 1;
                        const existingFiles = JSON.parse(localStorage.getItem('sensitiveFiles') || '[]');
                        const fileTypes = ['doc', 'docx', 'xls', 'xlsx', 'pdf'];
                        const fileNames = ['新文件', '临时文件', '报告', '文档'];
                        const sensitiveTypes = ['个人信息', '商业机密', '财务数据'];
                        const riskLevels = ['低', '中', '高'];
                        
                        for (let i = 0; i < newFilesCount; i++) {
                            const fileName = fileNames[Math.floor(Math.random() * fileNames.length)];
                            const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)];
                            const sensitiveType = sensitiveTypes[Math.floor(Math.random() * sensitiveTypes.length)];
                            const riskLevel = riskLevels[Math.floor(Math.random() * riskLevels.length)];
                            
                            existingFiles.push({
                                id: `sensitive-file-${Date.now()}-${i}`,
                                filename: `${fileName}_${Date.now()}.${fileType}`,
                                type: fileType,
                                sensitiveType: sensitiveType,
                                riskLevel: riskLevel,
                                detectedDate: new Date().toISOString(),
                                status: '未处理'
                            });
                        }
                        
                        localStorage.setItem('sensitiveFiles', JSON.stringify(existingFiles));
                        updateSensitiveFileStats();
                        hideLoading();
                        
                        // 显示成功消息
                        showToast('敏感文件扫描完成，发现 ' + newFilesCount + ' 个新敏感文件', 'success');
                    }, 2000);
                });
            }
            
            if (viewBtn) {
                viewBtn.addEventListener('click', function() {
                    // 这里可以打开敏感文件列表模态框
                    // 暂时显示模拟的文件列表
                    const files = JSON.parse(localStorage.getItem('sensitiveFiles') || '[]');
                    console.log('敏感文件列表:', files);
                    showToast('敏感文件列表已在控制台显示', 'info');
                });
            }
        }
        
        // 更新敏感文件统计数据
        function updateSensitiveFileStats() {
            const files = JSON.parse(localStorage.getItem('sensitiveFiles') || '[]');
            
            const totalCount = files.length;
            const highRiskCount = files.filter(function(file) {
                return file.riskLevel === '高';
            }).length;
            const sensitiveTypes = new Set(files.map(function(file) {
                return file.sensitiveType;
            })).size;
            
            const countEl = getElement('sensitive-file-count');
            const highRiskEl = getElement('high-risk-files');
            const typesEl = getElement('sensitive-types');
            
            if (countEl) countEl.textContent = totalCount;
            if (highRiskEl) highRiskEl.textContent = highRiskCount;
            if (typesEl) typesEl.textContent = sensitiveTypes;
        }
        
        // 文件溯源分析模块
        function initFileTraceModule() {
            // 初始化敏感文件分析
            initSensitiveFileAnalysis();
            
            // 初始化溯源方式切换
            initTraceMethods();
            
            // 初始化文件上传区域交互
            initFileUploadInteraction();
            
            // 初始化开始溯源按钮事件
            initStartTraceButton();
            
            // 初始化任务筛选事件
            // 确保函数已定义
            if (typeof initTaskFilters !== 'function') {
                function initTaskFilters() {
                    const timeFilter = getElement('task-time-filter');
                    const methodFilter = getElement('task-method-filter');
                    const typeFilter = getElement('task-type-filter');
                    
                    function updateFilters() {
                        const filters = {};
                        if (timeFilter) filters.timeRange = timeFilter.value;
                        if (methodFilter) filters.method = methodFilter.value;
                        if (typeFilter) filters.type = typeFilter.value;
                        loadTraceTasks(filters);
                    }
                    
                    if (timeFilter) timeFilter.addEventListener('change', updateFilters);
                    if (methodFilter) methodFilter.addEventListener('change', updateFilters);
                    if (typeFilter) typeFilter.addEventListener('change', updateFilters);
                }
            }
            initTaskFilters();
            
            // 加载历史溯源任务 - 使用已定义的函数
            loadTraceTasks();
            
            // 初始化分页功能
            // 确保函数已定义
            if (typeof initPagination !== 'function') {
                function initPagination() {
                    try {
                        // 这里简化处理，实际项目中需要根据数据量实现真正的分页
                        const pageBtns = document.querySelectorAll('.pagination .page-btn');
                        
                        if (pageBtns && pageBtns.length > 0) {
                            pageBtns.forEach(btn => {
                                if (btn) {
                                    btn.addEventListener('click', () => {
                                        // 移除所有活跃状态
                                        if (pageBtns) {
                                            pageBtns.forEach(b => {
                                                if (b && b.classList) {
                                                    b.classList.remove('active');
                                                }
                                            });
                                        }
                                        // 设置当前按钮活跃
                                        if (btn && btn.classList) {
                                            btn.classList.add('active');
                                        }
                                        // 这里可以添加分页逻辑
                                    });
                                }
                            });
                        }
                    } catch (error) {
                        console.error('初始化分页功能出错:', error);
                    }
                }
            }
            initPagination();
        }

        // 验证文件类型
        function validateFileTypes(files) {
            const allowedTypes = ['doc', 'docx', 'xls', 'xlsx', 'pdf'];
            const invalidFiles = [];
            
            Array.from(files).forEach(file => {
                const fileExt = file.name.split('.').pop().toLowerCase();
                if (!allowedTypes.includes(fileExt)) {
                    invalidFiles.push(file.name);
                }
            });
            
            return { valid: invalidFiles.length === 0, invalidFiles };
        }
        
        // 验证文件大小
        function validateFileSize(files, maxSizeMB = 10) {
            const maxSize = maxSizeMB * 1024 * 1024;
            const oversizedFiles = [];
            
            Array.from(files).forEach(file => {
                if (file.size > maxSize) {
                    oversizedFiles.push(file.name);
                }
            });
            
            return { valid: oversizedFiles.length === 0, oversizedFiles, maxSizeMB };
        }
        
        // 初始化文件上传交互
        function initFileUploadInteraction() {
            const uploadArea = getElement('file-upload-area');
            const fileInput = getElement('file-upload');
            
            if (uploadArea && fileInput) {
                // 点击上传区域触发文件选择
                uploadArea.addEventListener('click', function() {
                    fileInput.click();
                });
                
                // 处理文件选择
                function handleFiles(files) {
                    // 验证文件类型
                    const typeValidation = validateFileTypes(files);
                    if (!typeValidation.valid) {
                        showToast('不支持的文件类型: ' + typeValidation.invalidFiles.join(', '), 'error');
                        return false;
                    }
                    
                    // 验证文件大小
                    const sizeValidation = validateFileSize(files);
                    if (!sizeValidation.valid) {
                        showToast('文件大小超过限制 (' + sizeValidation.maxSizeMB + 'MB): ' + sizeValidation.oversizedFiles.join(', '), 'error');
                        return false;
                    }
                    
                    // 显示选择的文件信息
                    const fileNames = Array.from(files).map(function(file) {
                        return file.name;
                    }).join(', ');
                    const fileInfo = document.createElement('div');
                    fileInfo.className = 'file-info';
                    fileInfo.innerHTML = `
                        <p>已选择 ${files.length} 个文件</p>
                        <p class="text-xs text-secondary">${fileNames}</p>
                    `;
                    
                    // 移除之前的文件信息
                    const existingInfo = uploadArea.querySelector('.file-info');
                    if (existingInfo) {
                        uploadArea.removeChild(existingInfo);
                    }
                    
                    // 添加新的文件信息
                    uploadArea.appendChild(fileInfo);
                    return true;
                }
                
                // 显示选择的文件信息
                fileInput.addEventListener('change', function(e) {
                    if (e.target.files.length > 0) {
                        handleFiles(e.target.files);
                    }
                });
            }
            
            // 拖拽上传功能
            if (uploadArea) {
                uploadArea.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    uploadArea.classList.add('hover');
                });
                
                uploadArea.addEventListener('dragleave', function() {
                    uploadArea.classList.remove('hover');
                });
                
                uploadArea.addEventListener('drop', function(e) {
                    e.preventDefault();
                    uploadArea.classList.remove('hover');
                    
                    if (e.dataTransfer.files.length > 0 && fileInput) {
                        if (handleFiles(e.dataTransfer.files)) {
                            fileInput.files = e.dataTransfer.files;
                        }
                    }
                });
            }
        }

        // 初始化开始溯源按钮事件
        function initStartTraceButton() {
            const startTraceBtn = getElement('start-trace-btn');
            
            if (startTraceBtn) {
                startTraceBtn.addEventListener('click', function() {
                    const checkedMethod = document.querySelector('input[name="trace-method"]:checked');
                    const traceMethod = checkedMethod ? checkedMethod.value : '';
                    const traceTypeSelect = getElement('trace-type');
                    const traceType = traceTypeSelect ? traceTypeSelect.value : '';
                    
                    if (!traceMethod) {
                        showToast('请选择溯源方式', 'error');
                        return;
                    }
                    
                    let taskData = {
                        id: generateTaskId(),
                        method: traceMethod,
                        type: traceType,
                        timestamp: new Date().toISOString(),
                        status: '处理中',
                        details: {}
                    };
                    
                    // 根据溯源方式获取数据
                    let isValid = true;
                    switch(traceMethod) {
                        case 'file-upload':
                            const fileInput = getElement('file-upload');
                            if (fileInput && fileInput.files && fileInput.files.length === 0) {
                                showToast('请选择要上传的文件', 'error');
                                isValid = false;
                            } else if (fileInput && fileInput.files) {
                                // 再次验证文件（双重保障）
                                const typeValidation = validateFileTypes(fileInput.files);
                                const sizeValidation = validateFileSize(fileInput.files);
                                
                                if (!typeValidation.valid) {
                                    showToast('不支持的文件类型: ' + typeValidation.invalidFiles.join(', '), 'error');
                                    isValid = false;
                                } else if (!sizeValidation.valid) {
                                    showToast('文件大小超过限制 (' + sizeValidation.maxSizeMB + 'MB): ' + sizeValidation.oversizedFiles.join(', '), 'error');
                                    isValid = false;
                                } else {
                                    taskData.details.files = Array.from(fileInput.files).map(file => ({
                                        name: file.name,
                                        type: file.type,
                                        size: file.size,
                                        extension: file.name.split('.').pop().toLowerCase()
                                    }));
                                }
                            }
                            break;
                        case 'content-fragment':
                            const contentFragmentEl = getElement('content-fragment');
                            const contentFragment = contentFragmentEl ? contentFragmentEl.value.trim() : '';
                            if (!contentFragment) {
                                showToast('请输入文件内容片段', 'error');
                                isValid = false;
                            } else if (contentFragment.length < 10) {
                                showToast('内容片段长度不能少于10个字符', 'error');
                                isValid = false;
                            } else {
                                taskData.details.content = contentFragment;
                            }
                            break;
                        case 'word-segment':
                            const wordSegmentEl = getElement('word-segment-input');
                            const wordSegment = wordSegmentEl ? wordSegmentEl.value.trim() : '';
                            if (!wordSegment) {
                                showToast('请输入文件内容分词', 'error');
                                isValid = false;
                            } else {
                                const words = wordSegment.split(',').map(word => word.trim()).filter(word => word.length > 0);
                                if (words.length === 0) {
                                    showToast('请输入有效的分词（用逗号分隔）', 'error');
                                    isValid = false;
                                } else {
                                    taskData.details.words = words;
                                }
                            }
                            break;
                    }
                    
                    if (isValid) {
                        // 显示加载状态
                        showLoading('正在创建溯源任务...');
                        
                        // 创建新任务
                        createTraceTask(taskData);
                        
                        // 模拟处理完成
                        setTimeout(() => {
                            hideLoading();
                            updateTaskStatus(taskData.id, '完成');
                            showToast('溯源任务已完成', 'success');
                        }, 2500);
                    }
                });
            }
        }

        // 显示提示消息
        function showToast(message, type = 'info') {
            // 检查是否已存在toast容器
            let toastContainer = document.getElementById('toast-container');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.id = 'toast-container';
                toastContainer.className = 'fixed top-4 right-4 z-50 flex flex-col gap-2';
                document.body.appendChild(toastContainer);
            }
            
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `toast p-4 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full`;
            
            // 设置样式根据类型
            switch(type) {
                case 'success':
                    toast.style.backgroundColor = 'rgba(10, 132, 255, 0.9)';
                    toast.style.color = 'white';
                    break;
                case 'error':
                    toast.style.backgroundColor = 'rgba(255, 69, 58, 0.9)';
                    toast.style.color = 'white';
                    break;
                case 'warning':
                    toast.style.backgroundColor = 'rgba(255, 149, 0, 0.9)';
                    toast.style.color = 'white';
                    break;
                default:
                    toast.style.backgroundColor = 'rgba(58, 58, 60, 0.9)';
                    toast.style.color = 'white';
            }
            
            toast.textContent = message;
            toastContainer.appendChild(toast);
            
            // 显示toast
            setTimeout(() => {
                toast.classList.remove('translate-x-full');
                toast.classList.add('translate-x-0');
            }, 10);
            
            // 3秒后隐藏toast
            setTimeout(() => {
                toast.classList.remove('translate-x-0');
                toast.classList.add('translate-x-full');
                setTimeout(() => {
                    if (toast.parentNode === toastContainer) {
                        toastContainer.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }
        
        // 显示加载状态
        function showLoading(message = '加载中...') {
            // 检查是否已存在loading容器
            let loadingContainer = document.getElementById('loading-container');
            if (!loadingContainer) {
                loadingContainer = document.createElement('div');
                loadingContainer.id = 'loading-container';
                loadingContainer.className = 'fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm z-50 flex items-center justify-center';
                document.body.appendChild(loadingContainer);
            }
            
            // 创建加载内容
            const loadingContent = document.createElement('div');
            loadingContent.className = 'bg-white bg-opacity-90 p-6 rounded-lg shadow-xl flex flex-col items-center gap-3';
            loadingContent.innerHTML = `
                <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
                <p class="text-gray-700">${message}</p>
            `;
            
            loadingContainer.appendChild(loadingContent);
        }
        
        // 隐藏加载状态
        function hideLoading() {
            const loadingContainer = document.getElementById('loading-container');
            if (loadingContainer) {
                while (loadingContainer.firstChild) {
                    loadingContainer.removeChild(loadingContainer.firstChild);
                }
                document.body.removeChild(loadingContainer);
            }
        }
        
        // 生成任务ID
        function generateTaskId() {
            return 'TASK-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9).toUpperCase();
        }

        // 创建溯源任务
        // 任务详情模态框
        const taskDetailModalHTML = `
        <div id="task-detail-modal" class="dialog-overlay" style="display: none;">
            <div class="dialog-content" style="width: 600px; max-width: 90vw;">
                <h3 class="dialog-title">任务详情</h3>
                <div id="task-detail-content" class="task-detail-content"></div>
                <div class="dialog-actions">
                    <button id="task-detail-close" class="btn btn-primary">关闭</button>
                </div>
            </div>
        </div>
        `;
        
        // 添加任务详情模态框到页面
        document.body.insertAdjacentHTML('beforeend', taskDetailModalHTML);
        
        function createTraceTask(taskData) {
            try {
                // 获取现有任务列表
                let tasks = JSON.parse(localStorage.getItem('traceTasks') || '[]');
                
                // 添加新任务
                tasks.unshift(taskData);
                
                // 保存到localStorage
                localStorage.setItem('traceTasks', JSON.stringify(tasks));
                
                // 更新任务列表显示
                loadTraceTasks();
                
                // 显示成功提示
                showToast(`任务已创建，任务ID: ${taskData.id}`, 'success');
            } catch (error) {
                console.error('创建任务失败:', error);
                showToast('创建任务失败，请重试', 'error');
            }
        }

        // 更新任务状态
        function updateTaskStatus(taskId, status) {
            let tasks = JSON.parse(localStorage.getItem('traceTasks') || '[]');
            const taskIndex = tasks.findIndex(task => task.id === taskId);
            
            if (taskIndex !== -1) {
                tasks[taskIndex].status = status;
                localStorage.setItem('traceTasks', JSON.stringify(tasks));
                loadTraceTasks();
            }
        }

        // 分页状态
        let currentPage = 1;
        const pageSize = 10;
        let filteredTasks = [];
        
        // 加载溯源任务
        function loadTraceTasks(filters = {}) {
            let tasks = JSON.parse(localStorage.getItem('traceTasks') || '[]');
            
            // 应用筛选条件
            if (filters.timeRange) {
                const now = new Date();
                switch(filters.timeRange) {
                    case 'today':
                        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                        tasks = tasks.filter(task => new Date(task.timestamp) >= today);
                        break;
                    case '7d':
                        const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                        tasks = tasks.filter(task => new Date(task.timestamp) >= sevenDaysAgo);
                        break;
                }
            }
            
            if (filters.method && filters.method !== 'all') {
                tasks = tasks.filter(task => task.method === filters.method);
            }
            
            if (filters.type && filters.type !== 'all') {
                tasks = tasks.filter(task => task.type === filters.type);
            }
            
            // 保存筛选后的任务
            filteredTasks = tasks;
            // 重置到第一页
            currentPage = 1;
            // 渲染带分页的任务表格
            renderTraceTasksTableWithPagination();
        }
        
        // 渲染带分页的任务表格
        function renderTraceTasksTableWithPagination() {
            // 计算分页数据
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const currentPageTasks = filteredTasks.slice(startIndex, endIndex);
            
            // 渲染当前页任务
            renderTraceTasksTable(currentPageTasks);
            
            // 更新分页控件
            updatePaginationControls();
        }
        
        // 更新分页控件
        function updatePaginationControls() {
            const totalPages = Math.ceil(filteredTasks.length / pageSize);
            const paginationContainer = document.querySelector('.card.lg\:col-span-2 .pagination');
            
            if (!paginationContainer) return;
            
            // 清空现有分页控件
            paginationContainer.innerHTML = '';
            
            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.className = 'page-btn';
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage === 1;
            prevBtn.addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    renderTraceTasksTableWithPagination();
                }
            });
            paginationContainer.appendChild(prevBtn);
            
            // 页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
            
            // 调整开始页码以确保显示足够的页码
            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }
            
            // 首页按钮
            if (startPage > 1) {
                const firstPageBtn = document.createElement('button');
                firstPageBtn.className = 'page-btn';
                firstPageBtn.textContent = '1';
                if (currentPage === 1) firstPageBtn.classList.add('active');
                firstPageBtn.addEventListener('click', function() {
                    currentPage = 1;
                    renderTraceTasksTableWithPagination();
                });
                paginationContainer.appendChild(firstPageBtn);
                
                if (startPage > 2) {
                    const ellipsis1 = document.createElement('span');
                    ellipsis1.className = 'pagination-ellipsis';
                    ellipsis1.textContent = '...';
                    paginationContainer.appendChild(ellipsis1);
                }
            }
            
            // 中间页码
            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = 'page-btn';
                if (i === currentPage) pageBtn.classList.add('active');
                pageBtn.textContent = i;
                pageBtn.addEventListener('click', function() {
                    currentPage = i;
                    renderTraceTasksTableWithPagination();
                });
                paginationContainer.appendChild(pageBtn);
            }
            
            // 末页按钮
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    const ellipsis2 = document.createElement('span');
                    ellipsis2.className = 'pagination-ellipsis';
                    ellipsis2.textContent = '...';
                    paginationContainer.appendChild(ellipsis2);
                }
                
                const lastPageBtn = document.createElement('button');
                lastPageBtn.className = 'page-btn';
                lastPageBtn.textContent = totalPages;
                if (currentPage === totalPages) lastPageBtn.classList.add('active');
                lastPageBtn.addEventListener('click', function() {
                    currentPage = totalPages;
                    renderTraceTasksTableWithPagination();
                });
                paginationContainer.appendChild(lastPageBtn);
            }
            
            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.className = 'page-btn';
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.addEventListener('click', function() {
                if (currentPage < totalPages) {
                    currentPage++;
                    renderTraceTasksTableWithPagination();
                }
            });
            paginationContainer.appendChild(nextBtn);
        }

        // 渲染溯源任务表格
        function renderTraceTasksTable(tasks) {
            const tableBody = getElement('trace-tasks-table');
            
            if (!tableBody) return;
            
            tableBody.innerHTML = '';
            
            if (!tasks || tasks.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="empty-state">暂无历史任务</td>
                    </tr>
                `;
                return;
            }
            
            tasks.forEach(function(task) {
                if (!task) return;
                
                const methodText = task.method === 'file-upload' ? '导入文件' : 
                                  task.method === 'content-fragment' ? '内容片段' : 
                                  task.method === 'word-segment' ? '内容分词' : '未知方式';
                const typeText = task.type === 'tag' ? '标签溯源' : 
                                task.type === 'content' ? '内容溯源' : '未知类型';
                const statusClass = task.status === '处理中' ? 'badge-warning' : 
                                   task.status === '完成' ? 'badge-success' : 
                                   task.status === '失败' ? 'badge-danger' : 'badge-secondary';
                
                let formattedTime = '未知时间';
                try {
                    if (task.timestamp) {
                        formattedTime = new Date(task.timestamp).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        });
                    }
                } catch (e) {
                    console.error('日期格式化错误:', e);
                }
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${task.id || '未知ID'}</td>
                    <td>${methodText}</td>
                    <td>${typeText}</td>
                    <td>${formattedTime}</td>
                    <td><span class="badge ${statusClass}">${task.status || '未知状态'}</span></td>
                    <td>
                        <button class="btn btn-secondary btn-sm view-task" data-task-id="${task.id || ''}">查看</button>
                        <button class="btn btn-secondary btn-sm delete-task" data-task-id="${task.id || ''}">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 绑定查看和删除事件
            bindTaskActions();
        }

        // 绑定任务操作事件
        function bindTaskActions() {
            // 查看任务详情
            const viewButtons = document.querySelectorAll('.view-task');
            if (viewButtons) {
                viewButtons.forEach(function(btn) {
                    if (btn) {
                        btn.addEventListener('click', function(e) {
                            if (e?.currentTarget?.dataset?.taskId) {
                                const taskId = e.currentTarget.dataset.taskId;
                                viewTaskDetails(taskId);
                            }
                        });
                    }
                });
            }
            
            // 删除任务
            const deleteButtons = document.querySelectorAll('.delete-task');
            if (deleteButtons) {
                deleteButtons.forEach(function(btn) {
                    if (btn) {
                        btn.addEventListener('click', function(e) {
                            if (e?.currentTarget?.dataset?.taskId) {
                                const taskId = e.currentTarget.dataset.taskId;
                                if (confirm(`确定要删除任务 ${taskId} 吗？`)) {
                                    deleteTask(taskId);
                                }
                            }
                        });
                    }
                });
            }
        }

        // 查看任务详情
        function viewTaskDetails(taskId) {
            if (!taskId) {
                showToast('任务ID无效', 'error');
                return;
            }
            
            try {
                const tasks = JSON.parse(localStorage.getItem('traceTasks') || '[]');
                const task = tasks.find(function(t) {
                    return t?.id === taskId;
                });
                
                if (task) {
                    const modal = document.getElementById('task-detail-modal');
                    const content = document.getElementById('task-detail-content');
                    const closeBtn = document.getElementById('task-detail-close');
                    
                    if (modal && content) {
                        // 格式化时间
                        let formattedTime = '未知时间';
                        try {
                            if (task.timestamp) {
                                formattedTime = new Date(task.timestamp).toLocaleString('zh-CN', {
                                    year: 'numeric',
                                    month: '2-digit',
                                    day: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit'
                                });
                            }
                        } catch (e) {
                            console.error('日期格式化错误:', e);
                        }
                        
                        // 构建详情HTML
                        let detailsHTML = '<div class="task-detail-grid">';
                        detailsHTML += '<div class="detail-item"><label>任务ID:</label><span>' + (task.id || '未知ID') + '</span></div>';
                        detailsHTML += '<div class="detail-item"><label>溯源方式:</label><span>';
                        detailsHTML += task.method === 'file-upload' ? '导入文件' : 
                                      task.method === 'content-fragment' ? '内容片段' : 
                                      task.method === 'word-segment' ? '内容分词' : '未知方式';
                        detailsHTML += '</span></div>';
                        detailsHTML += '<div class="detail-item"><label>溯源类型:</label><span>';
                        detailsHTML += task.type === 'tag' ? '标签溯源' : 
                                      task.type === 'content' ? '内容溯源' : '未知类型';
                        detailsHTML += '</span></div>';
                        detailsHTML += '<div class="detail-item"><label>创建时间:</label><span>' + formattedTime + '</span></div>';
                        detailsHTML += '<div class="detail-item"><label>状态:</label><span>';
                        detailsHTML += '<span class="badge ';
                        detailsHTML += task.status === '处理中' ? 'badge-warning' : 
                                      task.status === '完成' ? 'badge-success' : 
                                      task.status === '失败' ? 'badge-danger' : 'badge-secondary';
                        detailsHTML += '">' + (task.status || '未知状态') + '</span></span></div>';
                        detailsHTML += '</div>';
                        
                        detailsHTML += '<div class="detail-section"><h4>详细信息</h4>';
                        
                        if (task.details) {
                            if (task.details.files && Array.isArray(task.details.files)) {
                                detailsHTML += '<div class="detail-subsection"><label>文件列表:</label><ul class="file-list">';
                                task.details.files.forEach(function(file) {
                                    detailsHTML += '<li>' + (file?.name || '未知文件') + ' (' + formatFileSize(file?.size || 0) + ')</li>';
                                });
                                detailsHTML += '</ul></div>';
                            } else if (task.details.content) {
                                const taskContent = task.details.content || '';
                                detailsHTML += '<div class="detail-subsection"><label>内容片段:</label><div class="content-preview">';
                                detailsHTML += taskContent.substring(0, 200) + (taskContent.length > 200 ? '...' : '');
                                detailsHTML += '</div></div>';
                            } else if (task.details.words && Array.isArray(task.details.words)) {
                                detailsHTML += '<div class="detail-subsection"><label>分词内容:</label><div class="word-tags">';
                                task.details.words.forEach(function(word) {
                                    detailsHTML += '<span class="word-tag">' + (word || '') + '</span>';
                                });
                                detailsHTML += '</div></div>';
                            }
                        }
                        
                        detailsHTML += '</div>';
                        
                        if (task.results && Array.isArray(task.results)) {
                            detailsHTML += '<div class="detail-section"><h4>溯源结果</h4><div class="trace-results">';
                            task.results.forEach(function(result, index) {
                                detailsHTML += '<div class="result-item"><h5>匹配项 ' + (index + 1) + '</h5><div class="result-info">';
                                detailsHTML += '<p><strong>文件ID:</strong> ' + (result?.fileId || '未知') + '</p>';
                                detailsHTML += '<p><strong>相似度:</strong> ' + (result?.similarity || 0) + '%</p>';
                                detailsHTML += '<p><strong>匹配内容:</strong> ' + (result?.matchedContent || '无') + '</p>';
                                detailsHTML += '</div></div>';
                            });
                            detailsHTML += '</div></div>';
                        }
                        
                        // 设置内容
                        content.innerHTML = detailsHTML;
                        
                        // 显示模态框
                        modal.style.display = 'flex';
                        
                        // 绑定关闭事件
                        if (closeBtn) {
                            closeBtn.onclick = function() {
                                modal.style.display = 'none';
                            };
                        }
                        
                        // 点击模态框外部关闭
                        modal.onclick = function(e) {
                            if (e.target === modal) {
                                modal.style.display = 'none';
                            }
                        };
                        
                        // ESC键关闭
                        document.addEventListener('keydown', function handleEsc(e) {
                            if (e.key === 'Escape') {
                                modal.style.display = 'none';
                                document.removeEventListener('keydown', handleEsc);
                            }
                        });
                    }
                } else {
                    showToast('未找到任务详情', 'error');
                }
            } catch (error) {
                console.error('查看任务详情失败:', error);
                showToast('查看任务详情失败', 'error');
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 添加任务详情相关样式
        const taskDetailStyles = document.createElement('style');
        taskDetailStyles.textContent = `
            .task-detail-content {
                padding: 20px 0;
            }
            
            .task-detail-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 15px;
                margin-bottom: 20px;
            }
            
            .detail-item {
                display: flex;
                flex-direction: column;
            }
            
            .detail-item label {
                font-weight: 600;
                color: #64748b;
                margin-bottom: 5px;
                font-size: 14px;
            }
            
            .detail-item span {
                font-size: 14px;
                color: #334155;
            }
            
            .detail-section {
                margin-bottom: 20px;
            }
            
            .detail-section h4 {
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 15px;
                color: #334155;
                border-bottom: 1px solid #e2e8f0;
                padding-bottom: 8px;
            }
            
            .detail-subsection {
                margin-bottom: 15px;
            }
            
            .detail-subsection label {
                display: block;
                font-weight: 600;
                color: #64748b;
                margin-bottom: 8px;
                font-size: 14px;
            }
            
            .file-list {
                list-style: disc;
                padding-left: 20px;
            }
            
            .file-list li {
                font-size: 14px;
                margin-bottom: 5px;
                color: #334155;
            }
            
            .content-preview {
                background-color: #f8fafc;
                padding: 10px;
                border-radius: 6px;
                border: 1px solid #e2e8f0;
                font-size: 14px;
                line-height: 1.6;
                color: #334155;
                max-height: 150px;
                overflow-y: auto;
            }
            
            .word-tags {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }
            
            .word-tag {
                background-color: #e0f2fe;
                color: #0369a1;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 13px;
            }
            
            .trace-results {
                display: flex;
                flex-direction: column;
                gap: 15px;
            }
            
            .result-item {
                background-color: #f8fafc;
                padding: 15px;
                border-radius: 8px;
                border: 1px solid #e2e8f0;
            }
            
            .result-item h5 {
                font-size: 15px;
                font-weight: 600;
                margin-bottom: 10px;
                color: #334155;
            }
            
            .result-info p {
                font-size: 14px;
                margin-bottom: 5px;
                color: #64748b;
            }
            
            .result-info strong {
                color: #334155;
            }
        `;
        document.head.appendChild(taskDetailStyles);

        // 删除任务
        function deleteTask(taskId) {
            if (!taskId) {
                console.error('任务ID无效');
                return;
            }
            
            try {
                let tasks = JSON.parse(localStorage.getItem('traceTasks') || '[]');
                tasks = tasks.filter(task => task?.id !== taskId);
                localStorage.setItem('traceTasks', JSON.stringify(tasks));
                loadTraceTasks();
            } catch (error) {
                console.error('删除任务出错:', error);
                alert('删除任务失败，请稍后重试');
            }
        }

        // 初始化任务筛选
        function initTaskFilters() {
            const timeFilter = getElement('task-time-filter');
            const methodFilter = getElement('task-method-filter');
            const typeFilter = getElement('task-type-filter');
            
            function updateFilters() {
                const filters = {};
                if (timeFilter) filters.timeRange = timeFilter.value;
                if (methodFilter) filters.method = methodFilter.value;
                if (typeFilter) filters.type = typeFilter.value;
                loadTraceTasks(filters);
            }
            
            if (timeFilter) timeFilter.addEventListener('change', updateFilters);
            if (methodFilter) methodFilter.addEventListener('change', updateFilters);
            if (typeFilter) typeFilter.addEventListener('change', updateFilters);
        }

        // 初始化分页功能
        function initPagination() {
            try {
                // 这里简化处理，实际项目中需要根据数据量实现真正的分页
                const pageBtns = document.querySelectorAll('.pagination .page-btn');
                
                if (pageBtns && pageBtns.length > 0) {
                    pageBtns.forEach(btn => {
                        if (btn) {
                            btn.addEventListener('click', () => {
                                // 移除所有活跃状态
                                if (pageBtns) {
                                    pageBtns.forEach(b => {
                                        if (b && b.classList) {
                                            b.classList.remove('active');
                                        }
                                    });
                                }
                                // 设置当前按钮活跃
                                if (btn && btn.classList) {
                                    btn.classList.add('active');
                                }
                                // 这里可以添加分页逻辑
                            });
                        }
                    });
                }
            } catch (error) {
                console.error('初始化分页功能出错:', error);
            }
        }

        // 初始化溯源方式切换
        function initTraceMethods() {
            const traceMethods = document.querySelectorAll('input[name="trace-method"]');
            
            function showSelectedMethod(method) {
                // 隐藏所有输入区域
                document.querySelectorAll('.trace-input-area').forEach(area => {
                    area.classList.add('hidden');
                });
                
                try {
                // 显示选中的输入区域
                const inputArea = document.getElementById(`${method}-input-area`);
                if (inputArea && inputArea.classList) {
                    inputArea.classList.remove('hidden');
                }
            } catch (error) {
                console.error(`显示方法${method}输入区域出错:`, error);
            }
        }
        
        try {
            // 为每个选项添加事件监听
            if (traceMethods && traceMethods.length > 0) {
                traceMethods.forEach(method => {
                    if (method) {
                        method.addEventListener('change', () => {
                            try {
                                if (method.checked) {
                                    showSelectedMethod(method.value);
                                }
                            } catch (error) {
                                console.error('处理跟踪方法变更事件出错:', error);
                            }
                        });
                    }
                });
            }
            
            // 默认显示第一个选项
            const defaultMethod = document.querySelector('input[name="trace-method"]:checked');
            if (defaultMethod) {
                showSelectedMethod(defaultMethod.value);
            }
        } catch (error) {
            console.error('初始化跟踪方法选项出错:', error);
        }
        }

        // 文件指纹库和分词词库管理模块
        function initLibrariesModule() {
            // 初始化文件指纹库
            initFileFingerprintLibrary();
            
            // 初始化分词词库
            initWordSegmentationLibrary();
            
            console.log('文件指纹库和分词词库模块初始化完成');
        }

        // 初始化文件指纹库
        function initFileFingerprintLibrary() {
            try {
                // 添加指纹库事件监听
                const addBtn = getElement('add-fingerprint-btn');
                const searchBtn = getElement('search-fingerprint-btn');
                
                if (addBtn) {
                    addBtn.addEventListener('click', addFingerprint);
                } else {
                    console.warn('添加指纹按钮元素未找到');
                }
                
                if (searchBtn) {
                    searchBtn.addEventListener('click', debouncedSearchFingerprint);
                } else {
                    console.warn('搜索指纹按钮元素未找到');
                }
                
                // 加载指纹库数据
                loadFingerprintLibrary();
            } catch (error) {
                console.error('初始化文件指纹库出错:', error);
            }
        }

        // 添加文件指纹
        function addFingerprint() {
            try {
                const fileNameInput = getElement('fingerprint-filename');
                const fileHashInput = getElement('fingerprint-hash');
                const fileTypeInput = getElement('fingerprint-type');
                
                // 验证DOM元素存在性
                if (!fileNameInput || !fileHashInput || !fileTypeInput) {
                    console.error('表单元素未找到');
                    ToastUtils.warning('系统错误：表单元素加载失败');
                    return;
                }
                
                const fileName = fileNameInput.value?.trim() || '';
                const fileHash = fileHashInput.value?.trim() || '';
                const fileType = fileTypeInput.value || 'unknown';
                
                if (!fileName || !fileHash) {
                    ToastUtils.warning('请填写文件名和文件指纹');
                    return;
                }
                
                // 输入格式验证
                if (fileName.length > 255) {
                    ToastUtils.warning('文件名长度不能超过255个字符');
                    return;
                }
                
                // 验证文件哈希格式（假设是MD5或SHA格式）
                const hashRegex = /^[a-fA-F0-9]{32,64}$/;
                if (!hashRegex.test(fileHash)) {
                    ToastUtils.warning('请输入有效的文件指纹（32-64位十六进制字符）');
                    return;
                }
            } catch (error) {
                console.error('添加文件指纹出错:', error);
                ToastUtils.error('添加指纹失败，请稍后重试');
            }
            
            // 创建指纹数据
            const fingerprint = {
                id: Date.now().toString(),
                filename: fileName,
                hash: fileHash,
                type: fileType,
                createdAt: new Date().toISOString(),
                status: '已验证'
            };
            
            // 获取现有指纹库
            let fingerprints = JSON.parse(localStorage.getItem('fileFingerprints') || '[]');
            
            // 检查重复
            if (fingerprints.some(fp => fp.hash === fileHash)) {
                ToastUtils.warning('该文件指纹已存在');
                return;
            }
            
            // 添加到指纹库
            fingerprints.unshift(fingerprint);
            localStorage.setItem('fileFingerprints', JSON.stringify(fingerprints));
            
            // 更新显示
            loadFingerprintLibrary();
            
            // 清空输入
            getElement('fingerprint-filename').value = '';
            getElement('fingerprint-hash').value = '';
            
            ToastUtils.success('文件指纹添加成功');
        }

        // 文件指纹搜索（带防抖优化）
        const debouncedSearchFingerprint = debounce(() => {
            const searchTerm = getElement('fingerprint-search')?.value.trim().toLowerCase() || '';
            const fingerprints = JSON.parse(localStorage.getItem('fileFingerprints') || '[]');
            
            let results;
            if (!searchTerm) {
                results = fingerprints;
            } else {
                results = fingerprints.filter(fp => 
                    fp.filename.toLowerCase().includes(searchTerm) || 
                    fp.hash.toLowerCase().includes(searchTerm)
                );
            }
            
            renderFingerprintTable(results);
        }, 300);
        
        // 文件指纹搜索入口
        function searchFingerprint() {
            debouncedSearchFingerprint();
        }

        // 加载文件指纹库
        function loadFingerprintLibrary() {
            try {
                // 安全地从localStorage获取并解析数据
                const storedData = localStorage.getItem('fileFingerprints');
                let fingerprints = [];
                
                if (storedData) {
                    try {
                        fingerprints = JSON.parse(storedData);
                        // 验证解析结果是否为数组
                        if (!Array.isArray(fingerprints)) {
                            console.error('文件指纹数据格式错误：不是有效数组');
                            fingerprints = [];
                        }
                    } catch (parseError) {
                        console.error('解析文件指纹数据出错:', parseError);
                        fingerprints = [];
                    }
                }
                
                // 调用渲染函数
                if (typeof renderFingerprintTable === 'function') {
                    renderFingerprintTable(fingerprints);
                } else {
                    console.error('渲染函数未定义');
                }
            } catch (error) {
                console.error('加载文件指纹库出错:', error);
            }
        }

        // 渲染指纹库表格
        function renderFingerprintTable(fingerprints) {
            try {
                const tableBody = document.getElementById('fingerprint-table');
                
                // 验证表格元素存在性
                if (!tableBody) {
                    console.error('指纹表格元素未找到');
                    return;
                }
                
                // 清空表格内容
                tableBody.innerHTML = '';
                
                // 确保fingerprints是数组
                const safeFingerprints = Array.isArray(fingerprints) ? fingerprints : [];
                
                if (safeFingerprints.length === 0) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="6" class="empty-state">暂无文件指纹数据</td>
                        </tr>
                    `;
                    return;
                }
                
                safeFingerprints.forEach(fp => {
                    // 跳过无效数据行
                    if (!fp) {
                        return;
                    }
                    
                    // 格式化日期，带错误处理
                    let formattedDate = '未知时间';
                    try {
                        if (fp.createdAt) {
                            formattedDate = new Date(fp.createdAt).toLocaleString('zh-CN');
                        }
                    } catch (dateError) {
                        console.warn('日期格式化出错:', dateError);
                    }
                    
                    const row = document.createElement('tr');
                    // 使用安全的属性访问和默认值
                    row.innerHTML = `
                        <td>${fp.filename || '未知文件名'}</td>
                        <td>${fp.hash || '未知哈希'}</td>
                        <td>${fp.type || '未知类型'}</td>
                        <td>${formattedDate}</td>
                        <td><span class="badge badge-success">${fp.status || '未知状态'}</span></td>
                        <td>
                        <button class="btn btn-secondary btn-sm delete-fingerprint" data-id="${fp.id || 'unknown'}">删除</button>
                      </td>
                    `;
                    
                    tableBody.appendChild(row);
                });
                
                // 绑定删除按钮事件
                try {
                    const deleteButtons = document.querySelectorAll('.delete-fingerprint');
                    if (deleteButtons) {
                        deleteButtons.forEach(button => {
                            if (button) {
                                button.addEventListener('click', function() {
                                    try {
                                        const id = this.getAttribute('data-id');
                                        if (id && id !== 'unknown') {
                                            deleteFingerprint(id);
                                        }
                                    } catch (err) {
                                        console.error('删除指纹按钮点击处理出错:', err);
                                    }
                                });
                            }
                        });
                    }
                } catch (bindError) {
                    console.error('绑定删除按钮事件出错:', bindError);
                }
            } catch (error) {
                console.error('渲染指纹表格出错:', error);
                // 显示错误状态
                const tableBody = document.getElementById('fingerprint-table');
                if (tableBody) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="6" class="empty-state">数据加载失败，请刷新页面重试</td>
                        </tr>
                    `;
                }
            }
            
            // 绑定删除事件
            document.querySelectorAll('.delete-fingerprint').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    deleteFingerprint(id);
                });
            });
        }

        // 删除文件指纹
        function deleteFingerprint(id) {
            try {
                // 验证ID
                if (!id || id === 'unknown' || typeof id !== 'string') {
                    console.error('无效的指纹ID');
                    ToastUtils.warning('删除失败：无效的操作');
                    return;
                }
                
                showConfirmDialog('确定要删除该文件指纹吗？', () => {
                    try {
                        // 安全地获取和解析数据
                        const storedData = localStorage.getItem('fileFingerprints');
                        let fingerprints = [];
                        
                        if (storedData) {
                            try {
                                fingerprints = JSON.parse(storedData);
                                if (!Array.isArray(fingerprints)) {
                                    console.error('文件指纹数据格式错误');
                                    fingerprints = [];
                                }
                            } catch (parseError) {
                                console.error('解析文件指纹数据出错:', parseError);
                                ToastUtils.error('数据读取失败');
                                return;
                            }
                        }
                        
                        // 过滤掉要删除的指纹
                        const updatedFingerprints = fingerprints.filter(fp => fp && fp.id !== id);
                        
                        // 保存更新后的数据
                        localStorage.setItem('fileFingerprints', JSON.stringify(updatedFingerprints));
                        
                        // 重新加载数据
                        if (typeof loadFingerprintLibrary === 'function') {
                            loadFingerprintLibrary();
                        }
                        
                        ToastUtils.success('文件指纹删除成功');
                    } catch (error) {
                        console.error('删除文件指纹处理出错:', error);
                        ToastUtils.error('删除失败，请稍后重试');
                    }
                });
            } catch (error) {
                console.error('删除文件指纹过程出错:', error);
            }
        }

        // 初始化分词词库
        function initWordSegmentationLibrary() {
            try {
                // 添加分词词库事件监听
                const addWordBtn = getElement('add-word-btn');
                const importWordsBtn = getElement('import-words-btn');
                const exportWordsBtn = getElement('export-words-btn');
                const searchWordBtn = getElement('search-word-btn');
                
                if (addWordBtn) {
                    addWordBtn.addEventListener('click', addWordToLibrary);
                } else {
                    console.warn('添加词语按钮未找到');
                }
                
                if (importWordsBtn) {
                    importWordsBtn.addEventListener('click', importWords);
                } else {
                    console.warn('导入词语按钮未找到');
                }
                
                if (exportWordsBtn) {
                    exportWordsBtn.addEventListener('click', exportWords);
                } else {
                    console.warn('导出词语按钮未找到');
                }
                
                if (searchWordBtn) {
                    searchWordBtn.addEventListener('click', searchWords);
                } else {
                    console.warn('搜索词语按钮未找到');
                }
                
                // 加载分词词库
                if (typeof loadWordLibrary === 'function') {
                    loadWordLibrary();
                } else {
                    console.error('加载词库函数未定义');
                }
            } catch (error) {
                console.error('初始化分词词库出错:', error);
            }
        }

        // 添加词语到词库
        function addWordToLibrary() {
            try {
                const wordInput = getElement('word-input');
                const categoryInput = getElement('word-category');
                const weightInput = getElement('word-weight');
                
                // 验证DOM元素存在性
                if (!wordInput || !categoryInput || !weightInput) {
                    console.error('词语输入表单元素未找到');
                    ToastUtils.warning('系统错误：表单元素加载失败');
                    return;
                }
                
                const word = wordInput.value?.trim() || '';
                const category = categoryInput.value || 'default';
                const weight = weightInput.value || '1';
                
                // 输入验证
                if (!word) {
                    ToastUtils.warning('请输入词语');
                    return;
                }
                
                // 词语长度验证
                if (word.length > 100) {
                    ToastUtils.warning('词语长度不能超过100个字符');
                    return;
                }
                
                // 权重数值验证
                if (weight && !/^\d+$/.test(weight)) {
                    ToastUtils.warning('请输入有效的权重数值');
                    return;
                }
                
                // 创建词语数据
                const wordData = {
                    id: Date.now().toString(),
                    word: word,
                    category: category,
                    weight: weight || '1',
                    createdAt: new Date().toISOString()
                };
              
              // 获取现有词库
              try {
                  const storedWords = localStorage.getItem('wordSegmentationLibrary');
                  let words = [];
                  
                  if (storedWords) {
                      try {
                          words = JSON.parse(storedWords);
                          if (!Array.isArray(words)) {
                              console.error('词库数据格式错误');
                              words = [];
                          }
                      } catch (parseError) {
                          console.error('解析词库数据出错:', parseError);
                          ToastUtils.error('数据读取失败');
                          return;
                      }
                  }
                  
                  // 检查重复
                  if (words.some(w => w && w.word === word && w.category === category)) {
                      ToastUtils.warning('该词语在当前分类下已存在');
                      return;
                  }
                  
                  // 添加到词库
                  words.unshift(wordData);
                  localStorage.setItem('wordSegmentationLibrary', JSON.stringify(words));
                  
                  // 更新显示
                  if (typeof loadWordLibrary === 'function') {
                      loadWordLibrary();
                  }
                  
                  // 清空输入
                  wordInput.value = '';
                  weightInput.value = '1';
                  
                  ToastUtils.success('词语添加成功');
              } catch (error) {
                  console.error('添加词语到词库出错:', error);
                  ToastUtils.error('添加失败，请稍后重试');
              }
            } catch (error) {
                console.error('添加词语过程出错:', error);
                ToastUtils.error('操作失败，请稍后重试');
            }
        }

        // 导入词语
        function importWords() {
            LoadingUtils.show('正在导入词语...');
            
            setTimeout(() => {
                const importText = getElement('words-import-text').value.trim();
                
                if (!importText) {
                    ToastUtils.warning('请输入要导入的词语，每行一个词语');
                    LoadingUtils.hide();
                    return;
                }
                
                const words = importText.split('\n').map(word => word.trim()).filter(word => word);
                const category = getElement('import-category').value;
                
                // 获取现有词库
                let wordLibrary = JSON.parse(localStorage.getItem('wordSegmentationLibrary') || '[]');
                let addedCount = 0;
                
                words.forEach(word => {
                    // 检查重复
                    if (!wordLibrary.some(w => w.word === word && w.category === category)) {
                        wordLibrary.unshift({
                            id: Date.now() + '-' + Math.random().toString(36).substr(2, 9),
                            word: word,
                            category: category,
                            weight: '1',
                            createdAt: new Date().toISOString()
                        });
                        addedCount++;
                    }
                });
                
                // 保存更新后的词库
                localStorage.setItem('wordSegmentationLibrary', JSON.stringify(wordLibrary));
                
                // 更新显示
                loadWordLibrary();
                
                // 清空导入文本
                getElement('words-import-text').value = '';
                
                ToastUtils.success(`成功导入 ${addedCount} 个词语`);
                LoadingUtils.hide();
            }, 500);
        }

        // 导出词语
        function exportWords() {
            LoadingUtils.show('正在准备导出数据...');
            
            setTimeout(() => {
                const wordLibrary = JSON.parse(localStorage.getItem('wordSegmentationLibrary') || '[]');
                const category = getElement('export-category').value;
                
                let wordsToExport = wordLibrary;
                if (category !== 'all') {
                    wordsToExport = wordLibrary.filter(w => w.category === category);
                }
                
                if (wordsToExport.length === 0) {
                    ToastUtils.warning('没有可导出的词语');
                    LoadingUtils.hide();
                    return;
                }
                
                // 构建导出文本
                const exportText = wordsToExport.map(w => `${w.word},${w.category},${w.weight}`).join('\n');
                
                // 创建下载链接
                const blob = new Blob([exportText], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `word_library_${category === 'all' ? 'all' : category}_${Date.now()}.txt`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                ToastUtils.success(`成功导出 ${wordsToExport.length} 个词语`);
                LoadingUtils.hide();
            }, 500);
        }

        // 搜索词语
        function searchWords() {
            const searchTerm = getElement('word-search').value.trim().toLowerCase();
            const category = getElement('word-search-category').value;
            const wordLibrary = JSON.parse(localStorage.getItem('wordSegmentationLibrary') || '[]');
            
            let results = wordLibrary;
            
            // 应用搜索条件
            if (category !== 'all') {
                results = results.filter(w => w.category === category);
            }
            
            if (searchTerm) {
                results = results.filter(w => w.word.toLowerCase().includes(searchTerm));
            }
            
            renderWordLibraryTable(results);
        }

        // 加载分词词库
        function loadWordLibrary() {
            try {
                // 安全获取和解析词库数据
                let wordLibrary = [];
                try {
                    const storedWords = localStorage.getItem('wordSegmentationLibrary');
                    if (storedWords) {
                        const parsed = JSON.parse(storedWords);
                        wordLibrary = Array.isArray(parsed) ? parsed : [];
                    }
                } catch (parseError) {
                    console.error('解析词库数据出错:', parseError);
                    wordLibrary = [];
                }
                
                // 验证渲染函数存在性
                if (typeof renderWordLibraryTable === 'function') {
                    renderWordLibraryTable(wordLibrary);
                } else {
                    console.error('renderWordLibraryTable 函数不存在');
                }
            } catch (error) {
                console.error('加载词库失败:', error);
                ToastUtils.error('加载词库失败，请刷新页面重试');
            }
        }

        // 渲染分词词库表格
        function renderWordLibraryTable(words) {
            try {
                // 验证表格元素
                const tableBody = getElement('word-library-table');
                if (!tableBody) {
                    console.error('词库表格元素不存在');
                    return;
                }
                
                tableBody.innerHTML = '';
                
                // 验证数据是否为数组
                const wordList = Array.isArray(words) ? words : [];
                
                if (wordList.length === 0) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="5" class="empty-state">暂无词语数据</td>
                        </tr>
                    `;
                    return;
                }
                
                wordList.forEach(word => {
                    try {
                        // 检查word对象是否有效
                        if (!word || typeof word !== 'object') {
                            console.warn('无效的词语对象，跳过:', word);
                            return;
                        }
                        
                        const categoryName = typeof getCategoryName === 'function' ? 
                            getCategoryName(word.category || 'unknown') : '未知分类';
                        
                        // 安全的日期格式化
                        let formattedDate = '未知日期';
                        try {
                            if (word.createdAt) {
                                formattedDate = new Date(word.createdAt).toLocaleString('zh-CN');
                            }
                        } catch (dateError) {
                            console.error('日期格式化错误:', dateError);
                        }
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${word.word || '未知词语'}</td>
                            <td>${categoryName}</td>
                            <td>${word.weight || '1'}</td>
                            <td>${formattedDate}</td>
                            <td>
                                <button class="btn btn-secondary btn-sm delete-word" data-id="${word.id || 'unknown'}">删除</button>
                            </td>
                        `;
                        
                        tableBody.appendChild(row);
                    } catch (wordError) {
                        console.error('处理词语数据时出错:', wordError);
                    }
                });
                
                // 绑定删除事件
                try {
                    document.querySelectorAll('.delete-word').forEach(btn => {
                        try {
                            btn.addEventListener('click', (e) => {
                                try {
                                    const id = e.currentTarget?.dataset?.id;
                                    if (id && id !== 'unknown' && typeof deleteWord === 'function') {
                                        deleteWord(id);
                                    } else {
                                        console.warn('词语ID无效或删除函数不存在');
                                    }
                                } catch (eventError) {
                                    console.error('删除事件处理失败:', eventError);
                                    ToastUtils.error('操作失败，请重试');
                                }
                            });
                        } catch (bindError) {
                            console.error('绑定删除事件失败:', bindError);
                        }
                    });
                } catch (selectorError) {
                    console.error('选择删除按钮时出错:', selectorError);
                }
            } catch (error) {
                console.error('渲染词库表格失败:', error);
                // 显示错误状态
                const tableBody = getElement('word-library-table');
                if (tableBody) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="5" class="error-state">加载数据失败，请刷新页面重试</td>
                        </tr>
                    `;
                }
            }

        // 获取分类名称
        function getCategoryName(categoryId) {
            const categories = {
                'default': '默认分类',
                'sensitive': '敏感词',
                'technical': '技术术语',
                'custom': '自定义'
            };
            return categories[categoryId] || categoryId;
        }

        // 删除词语
        function deleteWord(id) {
            try {
                // 验证ID
                if (!id || typeof id !== 'string' || id === 'unknown') {
                    console.error('无效的词语ID:', id);
                    ToastUtils.error('操作失败，数据无效');
                    return;
                }
                
                showConfirmDialog('确定要删除该词语吗？', () => {
                    try {
                        // 安全获取和解析词库数据
                        let wordLibrary = [];
                        try {
                            const storedWords = localStorage.getItem('wordSegmentationLibrary');
                            if (storedWords) {
                                const parsed = JSON.parse(storedWords);
                                wordLibrary = Array.isArray(parsed) ? parsed : [];
                            }
                        } catch (parseError) {
                            console.error('解析词库数据出错:', parseError);
                            wordLibrary = [];
                        }
                        
                        // 安全过滤和保存
                        try {
                            const updatedLibrary = wordLibrary.filter(w => w && w.id !== id);
                            localStorage.setItem('wordSegmentationLibrary', JSON.stringify(updatedLibrary));
                        } catch (storageError) {
                            console.error('保存词库数据失败:', storageError);
                            ToastUtils.error('保存失败，请稍后重试');
                            return;
                        }
                        
                        // 验证并调用加载函数
                        if (typeof loadWordLibrary === 'function') {
                            loadWordLibrary();
                        }
                        
                        ToastUtils.success('词语删除成功');
                    } catch (error) {
                        console.error('删除词语过程出错:', error);
                        ToastUtils.error('操作失败，请稍后重试');
                    }
                });
            } catch (error) {
                console.error('删除词语初始化失败:', error);
                ToastUtils.error('操作失败，请稍后重试');
            }
        }

        // 用户分群标签和可视化展示模块
        function initUserSegmentModule() {
            try {
                console.log('开始初始化用户分群标签和可视化模块');
                
                // 初始化用户分群标签管理
                if (typeof initUserSegmentTags === 'function') {
                    initUserSegmentTags();
                } else {
                    console.error('initUserSegmentTags 函数不存在');
                }
                
                // 初始化可视化图表
                if (typeof initVisualizationCharts === 'function') {
                    initVisualizationCharts();
                } else {
                    console.error('initVisualizationCharts 函数不存在');
                }
                
                // 初始化分群规则管理
                if (typeof initSegmentRules === 'function') {
                    initSegmentRules();
                } else {
                    console.error('initSegmentRules 函数不存在');
                }
                
                console.log('用户分群标签和可视化模块初始化完成');
            } catch (error) {
                console.error('用户分群模块初始化失败:', error);
                ToastUtils.error('用户分群模块初始化失败，请刷新页面重试');
            }
        }

        // 初始化用户分群标签管理
        function initUserSegmentTags() {
            try {
                // 添加标签按钮事件
                const addBtn = document.getElementById('add-segment-tag-btn');
                if (addBtn && typeof addSegmentTag === 'function') {
                    addBtn.addEventListener('click', addSegmentTag);
                } else {
                    console.warn('添加标签按钮不存在或添加标签函数未定义');
                }
                
                // 搜索标签事件
                const searchBtn = document.getElementById('search-segment-tag-btn');
                if (searchBtn && typeof searchSegmentTags === 'function') {
                    searchBtn.addEventListener('click', searchSegmentTags);
                } else {
                    console.warn('搜索标签按钮不存在或搜索标签函数未定义');
                }
                
                // 加载分群标签
                if (typeof loadSegmentTags === 'function') {
                    loadSegmentTags();
                } else {
                    console.error('loadSegmentTags 函数不存在');
                }
            } catch (error) {
                console.error('初始化用户分群标签管理失败:', error);
            }
        }

        // 添加分群标签
        function addSegmentTag() {
            try {
                // 验证DOM元素
                const tagNameInput = document.getElementById('segment-tag-name');
                const tagDescriptionInput = document.getElementById('segment-tag-description');
                const tagColorInput = document.getElementById('segment-tag-color');
                
                if (!tagNameInput || !tagDescriptionInput || !tagColorInput) {
                    console.error('分群标签表单元素不存在');
                    ToastUtils.error('操作失败，请刷新页面重试');
                    return;
                }
                
                // 获取并验证输入
                const tagName = tagNameInput.value?.trim() || '';
                const tagDescription = tagDescriptionInput.value?.trim() || '';
                const tagColor = tagColorInput.value || '#007bff';
                
                if (!tagName) {
                    ToastUtils.warning('请输入分群标签名称');
                    return;
                }
                
                if (tagName.length > 100) {
                    ToastUtils.warning('标签名称不能超过100个字符');
                    return;
                }
                
                // 创建标签数据
                const tagData = {
                    id: Date.now().toString() + '-' + Math.random().toString(36).substr(2, 9),
                    name: tagName,
                    description: tagDescription,
                    color: tagColor,
                    createdAt: new Date().toISOString(),
                    usageCount: 0
                };
                
                // 安全获取和解析现有标签
                let segmentTags = [];
                try {
                    const storedTags = localStorage.getItem('userSegmentTags');
                    if (storedTags) {
                        const parsed = JSON.parse(storedTags);
                        segmentTags = Array.isArray(parsed) ? parsed : [];
                    }
                } catch (parseError) {
                    console.error('解析标签数据出错:', parseError);
                    segmentTags = [];
                }
                
                // 检查重复
                if (segmentTags.some(tag => tag && tag.name === tagName)) {
                    ToastUtils.warning('该分群标签已存在');
                    return;
                }
                
                // 添加标签并保存
                try {
                    segmentTags.unshift(tagData);
                    localStorage.setItem('userSegmentTags', JSON.stringify(segmentTags));
                } catch (storageError) {
                    console.error('保存标签数据失败:', storageError);
                    ToastUtils.error('保存失败，请稍后重试');
                    return;
                }
                
                // 验证并调用加载函数
                if (typeof loadSegmentTags === 'function') {
                    loadSegmentTags();
                }
                
                // 清空输入
                tagNameInput.value = '';
                tagDescriptionInput.value = '';
                
                ToastUtils.success('分群标签添加成功');
            } catch (error) {
                console.error('添加分群标签失败:', error);
                ToastUtils.error('操作失败，请稍后重试');
            }
        }

        // 搜索分群标签
        function searchSegmentTags() {
            try {
                // 验证DOM元素
                const searchInput = document.getElementById('segment-tag-search');
                if (!searchInput) {
                    console.error('搜索输入框不存在');
                    ToastUtils.error('搜索功能不可用，请刷新页面重试');
                    return;
                }
                
                // 获取搜索词
                const searchTerm = searchInput.value?.trim()?.toLowerCase() || '';
                
                // 安全获取和解析标签数据
                let segmentTags = [];
                try {
                    const storedTags = localStorage.getItem('userSegmentTags');
                    if (storedTags) {
                        const parsed = JSON.parse(storedTags);
                        segmentTags = Array.isArray(parsed) ? parsed : [];
                    }
                } catch (parseError) {
                    console.error('解析标签数据出错:', parseError);
                    segmentTags = [];
                }
                
                // 应用搜索过滤
                if (searchTerm) {
                    segmentTags = segmentTags.filter(tag => 
                        tag && (
                            (tag.name && tag.name.toLowerCase().includes(searchTerm)) || 
                            (tag.description && tag.description.toLowerCase().includes(searchTerm))
                        )
                    );
                }
                
                // 验证并调用渲染函数
                if (typeof renderSegmentTagsTable === 'function') {
                    renderSegmentTagsTable(segmentTags);
                } else {
                    console.error('renderSegmentTagsTable 函数不存在');
                    ToastUtils.error('显示结果失败，请刷新页面重试');
                }
            } catch (error) {
                console.error('搜索分群标签失败:', error);
                ToastUtils.error('搜索失败，请稍后重试');
            }
        }

        // 加载分群标签
        function loadSegmentTags() {
            try {
                // 安全获取和解析标签数据
                let segmentTags = [];
                try {
                    const storedTags = localStorage.getItem('userSegmentTags');
                    if (storedTags) {
                        const parsed = JSON.parse(storedTags);
                        segmentTags = Array.isArray(parsed) ? parsed : [];
                    }
                } catch (parseError) {
                    console.error('解析标签数据出错:', parseError);
                    segmentTags = [];
                }
                
                // 验证并调用渲染函数
                if (typeof renderSegmentTagsTable === 'function') {
                    renderSegmentTagsTable(segmentTags);
                } else {
                    console.error('renderSegmentTagsTable 函数不存在');
                    ToastUtils.error('显示标签失败，请刷新页面重试');
                }
            } catch (error) {
                console.error('加载分群标签失败:', error);
                ToastUtils.error('加载标签失败，请刷新页面重试');
            }
        }

        // 渲染分群标签表格
        function renderSegmentTagsTable(tags) {
            try {
                // 验证表格元素
                const tableBody = document.getElementById('segment-tags-table');
                if (!tableBody) {
                    console.error('标签表格元素不存在');
                    return;
                }
                
                tableBody.innerHTML = '';
                
                // 验证数据是否为数组
                const tagList = Array.isArray(tags) ? tags : [];
                
                if (tagList.length === 0) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="5" class="empty-state">暂无分群标签数据</td>
                        </tr>
                    `;
                    return;
                }
                
                tagList.forEach(tag => {
                    try {
                        // 检查tag对象是否有效
                        if (!tag || typeof tag !== 'object') {
                            console.warn('无效的标签对象，跳过:', tag);
                            return;
                        }
                        
                        // 安全的日期格式化
                        let formattedDate = '未知日期';
                        try {
                            if (tag.createdAt) {
                                formattedDate = new Date(tag.createdAt).toLocaleString('zh-CN');
                            }
                        } catch (dateError) {
                            console.error('日期格式化错误:', dateError);
                        }
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>
                                <span class="tag-color" style="background-color: ${tag.color || '#999999'}; width: 20px; height: 20px; display: inline-block; border-radius: 4px;"></span>
                            </td>
                            <td>${tag.name || '未知标签'}</td>
                            <td>${tag.description || ''}</td>
                            <td>${formattedDate}</td>
                            <td>
                                <button class="btn btn-secondary btn-sm edit-segment-tag" data-id="${tag.id || 'unknown'}">编辑</button>
                                <button class="btn btn-secondary btn-sm delete-segment-tag" data-id="${tag.id || 'unknown'}">删除</button>
                            </td>
                        `;
                        
                        tableBody.appendChild(row);
                    } catch (tagError) {
                        console.error('处理标签数据时出错:', tagError);
                    }
                });
                
                // 绑定编辑和删除事件
                try {
                    // 绑定编辑事件
                    document.querySelectorAll('.edit-segment-tag').forEach(btn => {
                        try {
                            btn.addEventListener('click', function() {
                                try {
                                    const tagId = this.getAttribute('data-id');
                                    if (tagId && tagId !== 'unknown') {
                                        // 这里可以实现编辑功能
                                        console.log('编辑标签:', tagId);
                                    } else {
                                        console.warn('标签ID无效，无法编辑');
                                    }
                                } catch (eventError) {
                                    console.error('编辑事件处理失败:', eventError);
                                    ToastUtils.error('操作失败，请重试');
                                }
                            });
                        } catch (bindError) {
                            console.error('绑定编辑事件失败:', bindError);
                        }
                    });
                    
                    // 绑定删除事件
                    document.querySelectorAll('.delete-segment-tag').forEach(btn => {
                        try {
                            btn.addEventListener('click', function() {
                                try {
                                    const tagId = this.getAttribute('data-id');
                                    if (tagId && tagId !== 'unknown') {
                                        // 这里可以实现删除功能
                                        deleteSegmentTag(tagId);
                                    } else {
                                        console.warn('标签ID无效，无法删除');
                                    }
                                } catch (eventError) {
                                    console.error('删除事件处理失败:', eventError);
                                    ToastUtils.error('操作失败，请重试');
                                }
                            });
                        } catch (bindError) {
                            console.error('绑定删除事件失败:', bindError);
                        }
                    });
                } catch (selectorError) {
                    console.error('选择按钮时出错:', selectorError);
                }
            } catch (error) {
                console.error('渲染标签表格失败:', error);
                // 显示错误状态
                const tableBody = document.getElementById('segment-tags-table');
                if (tableBody) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="5" class="error-state">加载数据失败，请刷新页面重试</td>
                        </tr>
                    `;
                }
            }
        }            // 绑定编辑和删除事件
            bindSegmentTagActions();
        }

        // 绑定分群标签操作事件
        function bindSegmentTagActions() {
            // 编辑标签
            document.querySelectorAll('.edit-segment-tag').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    editSegmentTag(id);
                });
            });
            
            // 删除标签
            document.querySelectorAll('.delete-segment-tag').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    deleteSegmentTag(id);
                });
            });
        }

        // 编辑分群标签
        function editSegmentTag(id) {
            const segmentTags = JSON.parse(localStorage.getItem('userSegmentTags') || '[]');
            const tag = segmentTags.find(t => t.id === id);
            
            if (!tag) return;
            
            const newName = prompt('请输入新的标签名称:', tag.name);
            if (newName === null) return;
            
            if (!newName.trim()) {
                alert('标签名称不能为空');
                return;
            }
            
            // 检查名称重复（排除当前标签）
            if (segmentTags.some(t => t.name === newName.trim() && t.id !== id)) {
                alert('该标签名称已存在');
                return;
            }
            
            // 更新标签
            tag.name = newName.trim();
            const newDescription = prompt('请输入标签描述:', tag.description);
            if (newDescription !== null) {
                tag.description = newDescription.trim();
            }
            
            localStorage.setItem('userSegmentTags', JSON.stringify(segmentTags));
            loadSegmentTags();
            
            alert('标签更新成功');
        }

        // 删除分群标签
        function deleteSegmentTag(id) {
            try {
                // 验证ID参数
                if (!id || id === 'unknown' || typeof id !== 'string') {
                    console.error('无效的标签ID:', id);
                    ToastUtils.error('无效的操作参数');
                    return;
                }
                
                // 使用自定义确认框
                if (confirm('确定要删除该分群标签吗？')) {
                    // 安全地从localStorage获取并解析数据
                    let segmentTags = [];
                    try {
                        const storedTags = localStorage.getItem('userSegmentTags');
                        if (storedTags) {
                            const parsedTags = JSON.parse(storedTags);
                            segmentTags = Array.isArray(parsedTags) ? parsedTags : [];
                        }
                    } catch (parseError) {
                        console.error('解析标签数据失败:', parseError);
                        ToastUtils.error('数据读取失败');
                        return;
                    }
                    
                    // 检查标签是否存在
                    const tagExists = segmentTags.some(tag => tag.id === id);
                    if (!tagExists) {
                        console.warn('标签不存在:', id);
                        ToastUtils.warning('标签不存在或已被删除');
                        return;
                    }
                    
                    // 执行删除操作
                    try {
                        const updatedTags = segmentTags.filter(tag => tag.id !== id);
                        localStorage.setItem('userSegmentTags', JSON.stringify(updatedTags));
                        
                        // 验证loadSegmentTags函数是否存在
                        if (typeof loadSegmentTags === 'function') {
                            loadSegmentTags();
                        } else {
                            console.error('loadSegmentTags函数不存在');
                        }
                        
                        ToastUtils.success('标签删除成功');
                    } catch (storageError) {
                        console.error('保存数据失败:', storageError);
                        ToastUtils.error('保存操作失败');
                    }
                }
            } catch (error) {
                console.error('删除标签时发生错误:', error);
                ToastUtils.error('操作失败，请重试');
            }
        }

        // 初始化可视化图表
        function initVisualizationCharts() {
            try {
                console.log('开始初始化可视化图表');
                
                // 加载统计数据
                if (typeof loadStatisticsData === 'function') {
                    try {
                        loadStatisticsData();
                    } catch (statError) {
                        console.error('加载统计数据失败:', statError);
                    }
                } else {
                    console.error('loadStatisticsData函数不存在');
                }
                
                // 渲染用户分群分布图
                if (typeof renderSegmentDistribution === 'function') {
                    try {
                        renderSegmentDistribution();
                    } catch (distError) {
                        console.error('渲染分群分布图失败:', distError);
                    }
                } else {
                    console.error('renderSegmentDistribution函数不存在');
                }
                
                // 渲染标签关联网络图
                if (typeof renderTagRelationshipNetwork === 'function') {
                    try {
                        renderTagRelationshipNetwork();
                    } catch (networkError) {
                        console.error('渲染标签关联网络图失败:', networkError);
                    }
                } else {
                    console.error('renderTagRelationshipNetwork函数不存在');
                }
                
                // 渲染用户行为趋势图
                if (typeof renderUserBehaviorTrend === 'function') {
                    try {
                        renderUserBehaviorTrend();
                    } catch (trendError) {
                        console.error('渲染用户行为趋势图失败:', trendError);
                    }
                } else {
                    console.error('renderUserBehaviorTrend函数不存在');
                }
                
                // 绑定时间筛选事件
                try {
                    const timeFilterElement = document.getElementById('trend-time-filter');
                    if (timeFilterElement && typeof renderUserBehaviorTrend === 'function') {
                        timeFilterElement.addEventListener('change', function() {
                            try {
                                renderUserBehaviorTrend();
                            } catch (eventError) {
                                console.error('时间筛选事件处理失败:', eventError);
                                ToastUtils.error('数据刷新失败');
                            }
                        });
                    }
                } catch (bindError) {
                    console.error('绑定时间筛选事件失败:', bindError);
                }
                
                console.log('可视化图表初始化完成');
            } catch (error) {
                console.error('初始化可视化图表失败:', error);
            }
        }
        
        // 加载统计数据
        function loadStatisticsData() {
            try {
                // 安全地从localStorage获取并解析数据
                let userSegments = [];
                let segmentTags = [];
                
                try {
                    // 解析用户分群数据
                    const storedSegments = localStorage.getItem('userSegments');
                    if (storedSegments) {
                        const parsedSegments = JSON.parse(storedSegments);
                        userSegments = Array.isArray(parsedSegments) ? parsedSegments : [];
                    }
                    
                    // 解析标签数据
                    const storedTags = localStorage.getItem('userSegmentTags');
                    if (storedTags) {
                        const parsedTags = JSON.parse(storedTags);
                        segmentTags = Array.isArray(parsedTags) ? parsedTags : [];
                    }
                } catch (parseError) {
                    console.error('解析统计数据失败:', parseError);
                }
                
                // 计算总用户数
                try {
                    const totalUsers = userSegments.reduce((sum, segment) => {
                        return sum + (segment && typeof segment.count === 'number' ? segment.count : 0);
                    }, 0);
                    const totalUsersElement = document.getElementById('total-users');
                    if (totalUsersElement) {
                        totalUsersElement.textContent = totalUsers.toLocaleString();
                    }
                } catch (totalError) {
                    console.error('计算总用户数失败:', totalError);
                }
                
                // 显示标签总数
                try {
                    const totalTagsElement = document.getElementById('total-tags');
                    if (totalTagsElement) {
                        totalTagsElement.textContent = segmentTags.length;
                    }
                } catch (tagsError) {
                    console.error('显示标签总数失败:', tagsError);
                }
                
                // 计算高风险用户数
                try {
                    const highRiskSegment = userSegments.find(s => s && s.type === '高风险用户') || { count: 0 };
                    const highRiskUsersElement = document.getElementById('high-risk-users');
                    if (highRiskUsersElement) {
                        highRiskUsersElement.textContent = (typeof highRiskSegment.count === 'number' ? highRiskSegment.count : 0).toLocaleString();
                    }
                } catch (riskError) {
                    console.error('计算高风险用户数失败:', riskError);
                }
                
                // 模拟风险趋势
                try {
                    const riskTrendElement = document.getElementById('risk-trend');
                    if (riskTrendElement) {
                        riskTrendElement.textContent = '+12.5%';
                        riskTrendElement.style.color = 'var(--danger-color)';
                    }
                } catch (trendError) {
                    console.error('设置风险趋势失败:', trendError);
                }
            } catch (error) {
                console.error('加载统计数据时发生错误:', error);
            }
        }

        // 渲染用户分群分布图（模拟饼图）
        function renderSegmentDistribution() {
            try {
                console.log('开始渲染用户分群分布图');
                
                // 验证图表容器
                const chartContainer = document.getElementById('segment-distribution-chart');
                if (!chartContainer) {
                    console.error('分群分布图容器不存在');
                    return;
                }
                
                // 安全地从localStorage获取并解析数据
                let segmentData = [];
                try {
                    const storedSegments = localStorage.getItem('userSegments');
                    if (storedSegments) {
                        const parsedSegments = JSON.parse(storedSegments);
                        segmentData = Array.isArray(parsedSegments) ? parsedSegments : [];
                    }
                } catch (parseError) {
                    console.error('解析分群数据失败:', parseError);
                }
                
                // 如果没有数据，使用默认值
                if (segmentData.length === 0) {
                    segmentData = [
                        { id: '1', type: '高风险用户', count: 320, color: '#ff6b6b' },
                        { id: '2', type: '中等风险用户', count: 840, color: '#ffd166' },
                        { id: '3', type: '低风险用户', count: 1280, color: '#06d6a0' },
                        { id: '4', type: '可信用户', count: 2150, color: '#118ab2' }
                    ];
                }
                
                // 模拟饼图 - 简单实现
                let chartHTML = '';
                
                // 渲染图例
                try {
                    chartHTML = '<div class="chart-legend">';
                    segmentData.forEach(segment => {
                        if (segment && typeof segment === 'object') {
                            try {
                                // 安全计算百分比
                                const validSegments = segmentData.filter(s => s && typeof s.count === 'number');
                                const totalCount = validSegments.reduce((sum, s) => sum + s.count, 0);
                                const count = typeof segment.count === 'number' ? segment.count : 0;
                                const percentage = totalCount > 0 ? ((count / totalCount) * 100).toFixed(1) : '0.0';
                                
                                chartHTML += `
                                    <div class="legend-item">
                                        <span class="legend-color" style="background-color: ${segment.color || segment.type_color || '#999999'};"></span>
                                        <span class="legend-name">${segment.type || segment.name || '未知类型'}</span>
                                        <span class="legend-value">${count} (${percentage}%)</span>
                                    </div>
                                `;
                            } catch (legendError) {
                                console.error('渲染图例项失败:', legendError);
                            }
                        }
                    });
                    chartHTML += '</div>';
                } catch (legendSectionError) {
                    console.error('渲染图例失败:', legendSectionError);
                    chartHTML = '<div class="chart-legend"><div class="error-message">图例加载失败</div></div>';
                }
                
                // 渲染饼图
                try {
                    chartHTML += '<div class="chart-placeholder" style="display: flex; justify-content: center;">';
                    chartHTML += '<svg width="300" height="300" viewBox="0 0 300 300">';
                    
                    // 计算总用户数
                    const validSegments = segmentData.filter(s => s && typeof s.count === 'number');
                    const total = validSegments.reduce((sum, item) => sum + (item.count || 0), 0);
                    
                    if (total > 0) {
                        // 简单实现饼图
                        let startAngle = 0;
                        validSegments.forEach(segment => {
                            try {
                                const value = typeof segment.count === 'number' ? segment.count : 0;
                                const sliceAngle = (value / total) * 2 * Math.PI;
                                const endAngle = startAngle + sliceAngle;
                                const color = segment.color || segment.type_color || '#118ab2';
                                
                                // 计算圆弧路径，避免NaN
                                if (!isNaN(sliceAngle) && !isNaN(startAngle)) {
                                    const x1 = 150 + 120 * Math.cos(startAngle);
                                    const y1 = 150 + 120 * Math.sin(startAngle);
                                    const x2 = 150 + 120 * Math.cos(endAngle);
                                    const y2 = 150 + 120 * Math.sin(endAngle);
                                    const largeArcFlag = sliceAngle > Math.PI ? 1 : 0;
                                    
                                    // 添加过渡效果的路径
                                    chartHTML += `<path d="M 150,150 L ${x1},${y1} A 120,120 0 ${largeArcFlag},1 ${x2},${y2} Z" fill="${color}" opacity="0.8" stroke="white" stroke-width="2" transform-origin="150 150" style="transition: transform 0.3s ease;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'"/>`;
                                    
                                    // 计算标签位置（放在扇区中心）
                                    const labelAngle = startAngle + sliceAngle / 2;
                                    const labelRadius = 80;
                                    const labelX = 150 + labelRadius * Math.cos(labelAngle);
                                    const labelY = 150 + labelRadius * Math.sin(labelAngle);
                                    
                                    // 添加百分比标签
                                    const percentage = ((value / total) * 100).toFixed(0);
                                    chartHTML += `<text x="${labelX}" y="${labelY}" text-anchor="middle" dominant-baseline="middle" fill="white" font-weight="bold" font-size="14">${percentage}%</text>`;
                                }
                                
                                startAngle = endAngle;
                            } catch (sliceError) {
                                console.error('渲染饼图扇区失败:', sliceError);
                            }
                        });
                    } else {
                        // 显示无数据状态
                        chartHTML += `<text x="150" y="150" text-anchor="middle" dominant-baseline="middle" fill="#999" font-size="16">暂无数据</text>`;
                    }
                    
                    chartHTML += '</svg>';
                    chartHTML += '</div>';
                } catch (chartError) {
                    console.error('渲染饼图失败:', chartError);
                    chartHTML += '<div class="chart-placeholder"><div class="error-message">图表加载失败</div></div>';
                }
                
                // 安全地设置HTML
                chartContainer.innerHTML = chartHTML;
                console.log('用户分群分布图渲染完成');
            } catch (error) {
                console.error('渲染用户分群分布图时发生错误:', error);
                // 显示错误状态
                const chartContainer = document.getElementById('segment-distribution-chart');
                if (chartContainer) {
                    chartContainer.innerHTML = '<div class="chart-error">图表加载失败，请刷新页面重试</div>';
                }
            }
        }

        // 渲染标签关联网络图（模拟）
        function renderTagRelationshipNetwork() {
            try {
                console.log('开始渲染标签关联网络图');
                
                // 验证图表容器
                const chartContainer = document.getElementById('tag-relationship-network');
                if (!chartContainer) {
                    console.error('标签关联网络图容器不存在');
                    return;
                }
                
                // 安全地从localStorage获取并解析数据
                let tagData = [];
                let relationships = [];
                
                try {
                    // 解析标签数据
                    const storedTags = localStorage.getItem('tagRelationshipData');
                    if (storedTags) {
                        const parsedTags = JSON.parse(storedTags);
                        tagData = Array.isArray(parsedTags) ? parsedTags : [];
                    }
                    
                    // 解析关系数据
                    const storedRelationships = localStorage.getItem('tagRelationships');
                    if (storedRelationships) {
                        const parsedRelationships = JSON.parse(storedRelationships);
                        relationships = Array.isArray(parsedRelationships) ? parsedRelationships : [];
                    }
                } catch (parseError) {
                    console.error('解析标签关系数据失败:', parseError);
                }
                
                // 如果没有数据，使用默认值
                if (tagData.length === 0) {
                    tagData = [
                        { id: 1, name: '敏感操作', count: 150, category: '行为' },
                        { id: 2, name: '数据泄露', count: 120, category: '结果' },
                        { id: 3, name: '异常访问', count: 80, category: '行为' },
                        { id: 4, name: '权限提升', count: 60, category: '行为' },
                        { id: 5, name: '恶意代码', count: 40, category: '威胁' },
                        { id: 6, name: '数据篡改', count: 75, category: '结果' },
                        { id: 7, name: '暴力破解', count: 90, category: '攻击' }
                    ];
                    
                    relationships = [
                        { source: 1, target: 2, weight: 0.8 },
                        { source: 1, target: 3, weight: 0.6 },
                        { source: 3, target: 2, weight: 0.7 },
                        { source: 3, target: 4, weight: 0.5 },
                        { source: 4, target: 6, weight: 0.8 },
                        { source: 5, target: 2, weight: 0.6 },
                        { source: 5, target: 6, weight: 0.7 },
                        { source: 7, target: 3, weight: 0.9 },
                        { source: 7, target: 4, weight: 0.8 }
                    ];
                }
                
                // 颜色映射
                const categoryColors = {
                    '行为': '#118ab2',
                    '结果': '#ef476f',
                    '威胁': '#ffd166',
                    '攻击': '#06d6a0'
                };
                
                // 简单的力导向布局模拟
                const width = 400;
                const height = 300;
                const centerX = width / 2;
                const centerY = height / 2;
                
                // 为节点分配位置（简化版布局）
                let nodes = [];
                try {
                    nodes = tagData.map((tag, index) => {
                        if (tag && typeof tag === 'object') {
                            try {
                                // 使用极坐标分配位置
                                const angle = (index / tagData.length) * Math.PI * 2;
                                const radius = Math.min(width, height) * 0.3;
                                const count = typeof tag.count === 'number' ? tag.count : 0;
                                
                                return {
                                    ...tag,
                                    x: centerX + Math.cos(angle) * radius,
                                    y: centerY + Math.sin(angle) * radius,
                                    radius: Math.max(10, Math.min(30, Math.sqrt(count) * 2 + 5)), // 根据节点大小调整半径
                                    color: categoryColors[tag.category] || '#64748b'
                                };
                            } catch (nodeLayoutError) {
                                console.error('计算节点布局失败:', nodeLayoutError);
                                // 返回默认节点
                                return {
                                    ...tag,
                                    x: centerX,
                                    y: centerY,
                                    radius: 15,
                                    color: '#64748b'
                                };
                            }
                        }
                        return null;
                    }).filter(node => node !== null);
                } catch (nodesError) {
                    console.error('生成节点布局失败:', nodesError);
                }
                
                // 渲染网络图
                try {
                    let svgHTML = `
                        <svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
                            <!-- 背景 -->
                            <rect width="100%" height="100%" fill="white" fill-opacity="0.1" rx="8" ry="8" />
                            
                            <!-- 连接线 -->
                            ${relationships.map(rel => {
                                try {
                                    if (rel && typeof rel.source === 'number' && typeof rel.target === 'number') {
                                        const source = nodes.find(n => n && n.id === rel.source);
                                        const target = nodes.find(n => n && n.id === rel.target);
                                        
                                        if (source && target) {
                                            const weight = typeof rel.weight === 'number' ? rel.weight : 0.5;
                                            const strokeWidth = Math.max(1, Math.min(5, weight * 3));
                                            const opacity = Math.max(0.2, Math.min(0.9, 0.3 + weight * 0.7));
                                            
                                            return `<line 
                                                x1="${source.x}" y1="${source.y}" 
                                                x2="${target.x}" y2="${target.y}" 
                                                stroke="#64748b" 
                                                stroke-width="${strokeWidth}" 
                                                opacity="${opacity}"
                                                style="transition: all 0.3s ease;" 
                                                onmouseover="try { this.setAttribute('opacity', '0.9'); this.setAttribute('stroke', '#334155'); } catch(e) {};" 
                                                onmouseout="try { this.setAttribute('opacity', '${opacity}'); this.setAttribute('stroke', '#64748b'); } catch(e) {};"
                                            />`;
                                        }
                                    }
                                    return '';
                                } catch (lineError) {
                                    console.error('渲染连接线失败:', lineError);
                                    return '';
                                }
                            }).join('')}
                            
                            <!-- 节点 -->
                            ${nodes.map(node => {
                                try {
                                    if (node && typeof node.id === 'number') {
                                        return `
                                            <g>
                                                <circle 
                                                    cx="${node.x}" cy="${node.y}" r="${node.radius}" 
                                                    fill="${node.color}" 
                                                    fill-opacity="0.7" 
                                                    stroke="${node.color}" 
                                                    stroke-width="2" 
                                                    style="transition: all 0.3s ease; cursor: pointer;" 
                                                    onmouseover="try { this.setAttribute('fill-opacity', '0.9'); this.setAttribute('r', '${node.radius + 2}'); } catch(e) {};" 
                                                    onmouseout="try { this.setAttribute('fill-opacity', '0.7'); this.setAttribute('r', '${node.radius}'); } catch(e) {};"
                                                    onclick="try { showNodeDetails(${node.id}); } catch(e) {};"
                                                />
                                                <text 
                                                    x="${node.x}" y="${node.y}" 
                                                    text-anchor="middle" 
                                                    dominant-baseline="middle" 
                                                    font-size="11" 
                                                    fill="white" 
                                                    style="pointer-events: none;"
                                                >${node.name || '未知标签'}</text>
                                                <text 
                                                    x="${node.x}" y="${node.y + 15}" 
                                                    text-anchor="middle" 
                                                    font-size="9" 
                                                    fill="white" 
                                                    fill-opacity="0.8"
                                                    style="pointer-events: none;"
                                                >${node.count || 0}</text>
                                            </g>
                                        `;
                                    }
                                    return '';
                                } catch (nodeRenderError) {
                                    console.error('渲染节点失败:', nodeRenderError);
                                    return '';
                                }
                            }).join('')}
                            
                            <!-- 图例 -->
                            <g transform="translate(20, 20)">
                                <text font-size="12" font-weight="bold" fill="#334155" y="0">节点类型:</text>
                                ${Object.entries(categoryColors).map(([category, color], i) => {
                                    try {
                                        return `
                                            <g transform="translate(0, ${(i + 1) * 15})">
                                                <circle cx="0" cy="0" r="4" fill="${color}" fill-opacity="0.7" />
                                                <text x="10" y="4" font-size="10" fill="#334155">${category}</text>
                                            </g>
                                        `;
                                    } catch (legendError) {
                                        console.error('渲染图例失败:', legendError);
                                        return '';
                                    }
                                }).join('')}
                            </g>
                        </svg>
                    `;
                    
                    chartContainer.innerHTML = svgHTML;
                } catch (renderError) {
                    console.error('渲染SVG图表失败:', renderError);
                    chartContainer.innerHTML = '<div class="chart-placeholder"><div class="error-message">图表渲染失败</div></div>';
                }
                
                // 添加节点详情弹窗功能
                window.showNodeDetails = function(nodeId) {
                    try {
                        if (typeof nodeId !== 'number') {
                            console.error('无效的节点ID');
                            return;
                        }
                        
                        const node = nodes.find(n => n && n.id === nodeId);
                        if (!node) {
                            console.error('未找到节点:', nodeId);
                            return;
                        }
                        
                        // 显示节点详情（在实际项目中可以使用更复杂的弹窗）
                        const detailsHTML = `
                            <div style="
                                position: fixed;
                                background: rgba(255, 255, 255, 0.95);
                                border: 1px solid #e2e8f0;
                                border-radius: 8px;
                                padding: 15px;
                                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                                z-index: 1000;
                                left: 50%;
                                top: 50%;
                                transform: translate(-50%, -50%);
                                min-width: 250px;
                            ">
                                <h3 style="margin-top: 0; color: #334155;">${node.name || '未知标签'}</h3>
                                <p>类型: ${node.category || '未知类型'}</p>
                                <p>数量: ${node.count || 0}</p>
                                <button onclick="try { this.parentNode.remove(); } catch(e) {};" style="
                                    background: #118ab2;
                                    color: white;
                                    border: none;
                                    border-radius: 4px;
                                    padding: 5px 10px;
                                    cursor: pointer;
                                    margin-top: 10px;
                                ">关闭</button>
                            </div>
                        `;
                        
                        // 安全地将详情添加到文档中
                        const detailsContainer = document.createElement('div');
                        detailsContainer.innerHTML = detailsHTML;
                        const detailElement = detailsContainer.firstElementChild;
                        
                        if (detailElement) {
                            // 添加到文档并防止事件冒泡
                            document.body.appendChild(detailElement);
                            
                            // 添加点击外部关闭功能
                            const closeOnOutsideClick = function(event) {
                                try {
                                    if (detailElement && !detailElement.contains(event.target)) {
                                        document.body.removeChild(detailElement);
                                        document.removeEventListener('click', closeOnOutsideClick);
                                    }
                                } catch (e) {
                                    console.error('处理外部点击失败:', e);
                                }
                            };
                            
                            // 延迟添加事件监听器，避免立即触发
                            setTimeout(() => {
                                document.addEventListener('click', closeOnOutsideClick);
                            }, 0);
                        }
                    } catch (error) {
                        console.error('显示节点详情失败:', error);
                    }
                };
                
                console.log('标签关联网络图渲染完成');
            } catch (error) {
                console.error('渲染标签关联网络图时发生错误:', error);
                // 显示错误状态
                const chartContainer = document.getElementById('tag-relationship-network');
                if (chartContainer) {
                    chartContainer.innerHTML = '<div class="chart-error">图表加载失败，请刷新页面重试</div>';
                }
            }
        }

        // 渲染用户行为趋势图（模拟折线图）
        function renderUserBehaviorTrend() {
            const chartContainer = document.getElementById('user-behavior-trend');
            const timeFilter = document.getElementById('trend-time-filter')?.value || '6m';
            
            // 从localStorage获取数据，如果没有则使用默认数据
            let trendData = JSON.parse(localStorage.getItem('userBehaviorTrend') || '[]');
            
            // 如果没有数据，使用默认值
            if (trendData.length === 0) {
                // 根据时间筛选获取不同的数据
                switch(timeFilter) {
                    case '1m':
                        trendData = [
                            { date: '第1周', riskEvents: 120, normalEvents: 850 },
                            { date: '第2周', riskEvents: 135, normalEvents: 920 },
                            { date: '第3周', riskEvents: 110, normalEvents: 880 },
                            { date: '第4周', riskEvents: 145, normalEvents: 950 }
                        ];
                        break;
                    case '3m':
                        trendData = [
                            { date: '1月', riskEvents: 320, normalEvents: 3500 },
                            { date: '2月', riskEvents: 380, normalEvents: 3700 },
                            { date: '3月', riskEvents: 420, normalEvents: 3900 }
                        ];
                        break;
                    case '6m':
                    default:
                        trendData = [
                            { date: '1月', riskEvents: 320, normalEvents: 3500 },
                            { date: '2月', riskEvents: 380, normalEvents: 3700 },
                            { date: '3月', riskEvents: 420, normalEvents: 3900 },
                            { date: '4月', riskEvents: 480, normalEvents: 4100 },
                            { date: '5月', riskEvents: 450, normalEvents: 4200 },
                            { date: '6月', riskEvents: 520, normalEvents: 4400 }
                        ];
                }
            }
            
            const width = 400;
            const height = 250;
            const margin = { top: 20, right: 20, bottom: 40, left: 60 };
            const chartWidth = width - margin.left - margin.right;
            const chartHeight = height - margin.top - margin.bottom;
            
            // 计算最大值用于缩放
            const maxRiskValue = Math.max(...trendData.map(d => d.riskEvents)) * 1.2;
            const maxNormalValue = Math.max(...trendData.map(d => d.normalEvents)) * 1.2;
            
            // 计算点间距
            const pointSpacing = chartWidth / (trendData.length - 1);
            
            // 生成X轴点位置
            const getX = (index) => margin.left + index * pointSpacing;
            
            // 生成Y轴点位置（风险事件）
            const getY1 = (value) => height - margin.bottom - (value / maxRiskValue) * chartHeight;
            
            // 生成Y轴点位置（正常事件）
            const getY2 = (value) => height - margin.bottom - (value / maxNormalValue) * chartHeight;
            
            // 简单模拟折线图
            chartContainer.innerHTML = `
                <svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
                    <!-- 背景网格 -->
                    <g opacity="0.2">
                        <!-- 水平线 -->
                        ${[0, 0.25, 0.5, 0.75, 1].map((ratio, i) => {
                            const y = height - margin.bottom - ratio * chartHeight;
                            return `<line x1="${margin.left}" y1="${y}" x2="${width - margin.right}" y2="${y}" stroke="#333" stroke-width="1" />` +
                                   `<text x="${margin.left - 10}" y="${y + 4}" text-anchor="end" font-size="10">${Math.round(maxRiskValue * ratio)}</text>`;
                        }).join('')}
                        
                        <!-- 垂直线 -->
                        ${trendData.map((item, index) => {
                            const x = getX(index);
                            return `<line x1="${x}" y1="${margin.top}" x2="${x}" y2="${height - margin.bottom}" stroke="#333" stroke-width="1" />`;
                        }).join('')}
                    </g>
                    
                    <!-- 坐标轴 -->
                    <line x1="${margin.left}" y1="${height - margin.bottom}" x2="${width - margin.right}" y2="${height - margin.bottom}" stroke="#333" stroke-width="2" />
                    <line x1="${margin.left}" y1="${height - margin.bottom}" x2="${margin.left}" y2="${margin.top}" stroke="#333" stroke-width="2" />
                    
                    <!-- X轴标签 -->
                    ${trendData.map((item, index) => 
                        `<text x="${getX(index)}" y="${height - margin.bottom + 25}" text-anchor="middle" font-size="12">${item.date}</text>`
                    ).join('')}
                    
                    <!-- Y轴标签 -->
                    <text x="${margin.left / 2}" y="${height / 2}" text-anchor="middle" font-size="12" transform="rotate(-90, ${margin.left / 2}, ${height / 2})">事件数量</text>
                    
                    <!-- 图例 -->
                    <g transform="translate(${width - 180}, ${margin.top})">
                        <rect x="0" y="0" width="12" height="12" fill="#ff6b6b" />
                        <text x="15" y="10" font-size="12">风险事件</text>
                        <rect x="0" y="20" width="12" height="12" fill="#118ab2" />
                        <text x="15" y="30" font-size="12">正常事件</text>
                    </g>
                    
                    <!-- 正常事件数据线 -->
                    <polyline 
                        points="${trendData.map((item, index) => 
                            `${getX(index)},${getY2(item.normalEvents)}`
                        ).join(' ')}"
                        fill="none"
                        stroke="#118ab2"
                        stroke-width="2"
                        opacity="0.6"
                    />
                    
                    <!-- 风险事件数据线 -->
                    <polyline 
                        points="${trendData.map((item, index) => 
                            `${getX(index)},${getY1(item.riskEvents)}`
                        ).join(' ')}"
                        fill="none"
                        stroke="#ff6b6b"
                        stroke-width="3"
                    />
                    
                    <!-- 风险事件数据点 -->
                    ${trendData.map((item, index) => {
                        const x = getX(index);
                        const y = getY1(item.riskEvents);
                        return `
                            <circle cx="${x}" cy="${y}" r="5" fill="#ff6b6b" style="transition: r 0.2s ease;" onmouseover="this.r=8" onmouseout="this.r=5"/>
                            <text x="${x}" y="${y - 10}" text-anchor="middle" font-size="10" fill="#333">${item.riskEvents}</text>
                        `;
                    }).join('')}
                    
                    <!-- 正常事件数据点 -->
                    ${trendData.map((item, index) => {
                        const x = getX(index);
                        const y = getY2(item.normalEvents);
                        return `
                            <circle cx="${x}" cy="${y}" r="4" fill="#118ab2" opacity="0.8" style="transition: r 0.2s ease;" onmouseover="this.r=7" onmouseout="this.r=4"/>
                        `;
                    }).join('')}
                </svg>
            `;
        }

        // 初始化分群规则管理
        function initSegmentRules() {
            // 绑定添加规则按钮事件
            document.getElementById('add-segment-rule-btn').addEventListener('click', addSegmentRule);
            
            // 绑定搜索规则事件
            const searchInput = document.getElementById('segment-rule-search');
            if (searchInput) {
                searchInput.addEventListener('input', debouncedSearchSegmentRules);
            }
            
            // 加载规则数据
            loadSegmentRules();
        }

        // 添加分群规则
        function addSegmentRule() {
            const ruleName = document.getElementById('segment-rule-name').value.trim();
            const ruleConditions = document.getElementById('segment-rule-conditions').value.trim();
            
            if (!ruleName) {
                showNotification('请输入规则名称', 'error');
                return;
            }
            
            if (!ruleConditions) {
                showNotification('请输入规则条件', 'error');
                return;
            }
            
            // 创建规则数据
            const ruleData = {
                id: Date.now().toString(),
                name: ruleName,
                conditions: ruleConditions,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
                status: '启用',
                description: document.getElementById('segment-rule-description')?.value || ''
            };
            
            // 获取现有规则
            let segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
            
            // 检查规则名称是否重复
            if (segmentRules.some(rule => rule.name === ruleName)) {
                showNotification('规则名称已存在，请使用其他名称', 'error');
                return;
            }
            
            // 添加规则
            segmentRules.unshift(ruleData);
            localStorage.setItem('userSegmentRules', JSON.stringify(segmentRules));
            
            // 更新显示
            loadSegmentRules();
            
            // 清空输入
            clearRuleForm();
            
            showNotification('分群规则添加成功', 'success');
        }

        // 编辑分群规则
        function editSegmentRule(id) {
            const segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
            const rule = segmentRules.find(r => r.id === id);
            
            if (!rule) {
                showNotification('规则不存在', 'error');
                return;
            }
            
            // 填充编辑表单
            document.getElementById('segment-rule-name').value = rule.name;
            document.getElementById('segment-rule-conditions').value = rule.conditions;
            const descriptionElement = document.getElementById('segment-rule-description');
            if (descriptionElement) {
                descriptionElement.value = rule.description || '';
            }
            
            // 显示编辑模式
            const formHeader = document.querySelector('.segment-rule-form h4');
            if (formHeader) {
                formHeader.textContent = '编辑分群规则';
            }
            
            // 隐藏添加按钮，显示保存和取消按钮
            document.getElementById('add-segment-rule-btn').style.display = 'none';
            
            // 创建或显示保存和取消按钮
            let saveBtn = document.getElementById('save-segment-rule-btn');
            let cancelBtn = document.getElementById('cancel-edit-btn');
            
            if (!saveBtn) {
                saveBtn = document.createElement('button');
                saveBtn.id = 'save-segment-rule-btn';
                saveBtn.className = 'btn btn-primary';
                saveBtn.textContent = '保存修改';
                saveBtn.addEventListener('click', () => saveSegmentRule(id));
                
                cancelBtn = document.createElement('button');
                cancelBtn.id = 'cancel-edit-btn';
                cancelBtn.className = 'btn btn-secondary';
                cancelBtn.textContent = '取消';
                cancelBtn.addEventListener('click', cancelEditRule);
                
                const btnGroup = document.querySelector('.segment-rule-form .btn-group');
                if (btnGroup) {
                    btnGroup.appendChild(saveBtn);
                    btnGroup.appendChild(cancelBtn);
                }
            } else {
                saveBtn.style.display = 'inline-block';
                cancelBtn.style.display = 'inline-block';
                // 更新保存按钮的点击事件
                saveBtn.onclick = () => saveSegmentRule(id);
            }
            
            // 滚动到表单位置
            document.querySelector('.segment-rule-form').scrollIntoView({ behavior: 'smooth', block: 'center' });
        }

        // 保存分群规则修改
        function saveSegmentRule(id) {
            const ruleName = document.getElementById('segment-rule-name').value.trim();
            const ruleConditions = document.getElementById('segment-rule-conditions').value.trim();
            
            if (!ruleName) {
                showNotification('请输入规则名称', 'error');
                return;
            }
            
            if (!ruleConditions) {
                showNotification('请输入规则条件', 'error');
                return;
            }
            
            // 获取现有规则
            let segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
            const ruleIndex = segmentRules.findIndex(rule => rule.id === id);
            
            if (ruleIndex === -1) {
                showNotification('规则不存在', 'error');
                return;
            }
            
            // 检查规则名称是否与其他规则重复
            if (segmentRules.some((rule, index) => rule.name === ruleName && index !== ruleIndex)) {
                showNotification('规则名称已存在，请使用其他名称', 'error');
                return;
            }
            
            // 更新规则
            segmentRules[ruleIndex] = {
                ...segmentRules[ruleIndex],
                name: ruleName,
                conditions: ruleConditions,
                description: document.getElementById('segment-rule-description')?.value || '',
                updatedAt: new Date().toISOString()
            };
            
            localStorage.setItem('userSegmentRules', JSON.stringify(segmentRules));
            loadSegmentRules();
            cancelEditRule();
            
            showNotification('分群规则更新成功', 'success');
        }

        // 取消编辑
        function cancelEditRule() {
            clearRuleForm();
            
            // 恢复表单标题
            const formHeader = document.querySelector('.segment-rule-form h4');
            if (formHeader) {
                formHeader.textContent = '添加分群规则';
            }
            
            // 恢复按钮状态
            document.getElementById('add-segment-rule-btn').style.display = 'inline-block';
            
            const saveBtn = document.getElementById('save-segment-rule-btn');
            const cancelBtn = document.getElementById('cancel-edit-btn');
            if (saveBtn) saveBtn.style.display = 'none';
            if (cancelBtn) cancelBtn.style.display = 'none';
        }

        // 清空规则表单
        function clearRuleForm() {
            document.getElementById('segment-rule-name').value = '';
            document.getElementById('segment-rule-conditions').value = '';
            if (document.getElementById('segment-rule-description')) {
                document.getElementById('segment-rule-description').value = '';
            }
        }

        // 搜索分群规则（带防抖优化）
        const debouncedSearchSegmentRules = debounce(() => {
            const searchTerm = getElement('segment-rule-search')?.value.toLowerCase().trim() || '';
            const segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
            
            if (!searchTerm) {
                renderSegmentRulesTable(segmentRules);
                return;
            }
            
            // 根据名称、条件或描述搜索
            const filteredRules = segmentRules.filter(rule => 
                rule.name.toLowerCase().includes(searchTerm) ||
                (rule.conditions && rule.conditions.toLowerCase().includes(searchTerm)) ||
                (rule.description && rule.description.toLowerCase().includes(searchTerm))
            );
            
            renderSegmentRulesTable(filteredRules);
        }, 300);
        
        // 搜索分群规则入口
        function searchSegmentRules() {
            debouncedSearchSegmentRules();
        }

        // 加载分群规则
        function loadSegmentRules() {
            const segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
            renderSegmentRulesTable(segmentRules);
        }

        // 渲染分群规则表格
        function renderSegmentRulesTable(rules) {
            const tableBody = document.getElementById('segment-rules-table');
            tableBody.innerHTML = '';
            
            if (rules.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="empty-state">暂无分群规则数据</td>
                    </tr>
                `;
                return;
            }
            
            rules.forEach(rule => {
                const formattedDate = new Date(rule.createdAt).toLocaleString('zh-CN');
                const statusClass = rule.status === '启用' ? 'badge-success' : 'badge-warning';
                
                const row = document.createElement('tr');
                row.className = 'rule-row';
                row.innerHTML = `
                    <td class="rule-name">${rule.name}</td>
                    <td class="rule-conditions">${rule.conditions}</td>
                    <td class="rule-description">${rule.description || '-'}</td>
                    <td class="rule-date">${formattedDate}</td>
                    <td class="rule-status"><span class="badge ${statusClass}">${rule.status}</span></td>
                    <td class="rule-actions">
                        <button class="btn btn-info btn-sm edit-segment-rule" data-id="${rule.id}">编辑</button>
                        <button class="btn btn-secondary btn-sm toggle-rule-status" data-id="${rule.id}">${rule.status === '启用' ? '禁用' : '启用'}</button>
                        <button class="btn btn-danger btn-sm delete-segment-rule" data-id="${rule.id}">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 绑定事件
            bindSegmentRuleActions();
        }

        // 绑定分群规则操作事件
        function bindSegmentRuleActions() {
            // 编辑规则
            document.querySelectorAll('.edit-segment-rule').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    editSegmentRule(id);
                });
            });
            
            // 切换规则状态
            document.querySelectorAll('.toggle-rule-status').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    toggleRuleStatus(id);
                });
            });
            
            // 删除规则
            document.querySelectorAll('.delete-segment-rule').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    deleteSegmentRule(id);
                });
            });
        }

        // 切换规则状态
        function toggleRuleStatus(id) {
            let segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
            const ruleIndex = segmentRules.findIndex(rule => rule.id === id);
            
            if (ruleIndex !== -1) {
                const newStatus = segmentRules[ruleIndex].status === '启用' ? '禁用' : '启用';
                segmentRules[ruleIndex] = {
                    ...segmentRules[ruleIndex],
                    status: newStatus,
                    updatedAt: new Date().toISOString()
                };
                localStorage.setItem('userSegmentRules', JSON.stringify(segmentRules));
                loadSegmentRules();
                showNotification(`规则已${newStatus}`, 'success');
            }
        }

        // 创建确认对话框
        function showConfirmationDialog(title, message, onConfirm, onCancel) {
            // 检查是否已存在对话框，如果存在则移除
            const existingDialog = document.getElementById('custom-confirm-dialog');
            if (existingDialog) {
                existingDialog.remove();
            }
            
            // 创建对话框背景
            const dialogOverlay = document.createElement('div');
            dialogOverlay.className = 'dialog-overlay';
            dialogOverlay.id = 'custom-confirm-dialog';
            
            // 创建对话框内容
            dialogOverlay.innerHTML = `
                <div class="dialog-content">
                    <h3 class="dialog-title">${title}</h3>
                    <p class="dialog-message">${message}</p>
                    <div class="dialog-actions">
                        <button id="dialog-cancel" class="btn btn-secondary">取消</button>
                        <button id="dialog-confirm" class="btn btn-danger">确定</button>
                    </div>
                </div>
            `;
            
            // 添加对话框样式
            const style = document.createElement('style');
            style.textContent = `
                .dialog-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: rgba(0, 0, 0, 0.5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 1000;
                    animation: fadeIn 0.3s ease;
                }
                
                .dialog-content {
                    background-color: white;
                    border-radius: var(--radius-medium);
                    padding: var(--spacing-lg);
                    box-shadow: var(--shadow-hover);
                    width: 90%;
                    max-width: 400px;
                    animation: slideUp 0.3s ease;
                }
                
                .dialog-title {
                    margin-top: 0;
                    color: var(--color-text-primary);
                    font-size: 1.2rem;
                }
                
                .dialog-message {
                    color: var(--color-text-secondary);
                    margin-bottom: var(--spacing-md);
                }
                
                .dialog-actions {
                    display: flex;
                    justify-content: flex-end;
                    gap: var(--spacing-sm);
                    margin-top: var(--spacing-md);
                }
                
                @keyframes slideUp {
                    from {
                        transform: translateY(20px);
                        opacity: 0;
                    }
                    to {
                        transform: translateY(0);
                        opacity: 1;
                    }
                }
            `;
            document.head.appendChild(style);
            
            // 添加到页面
            document.body.appendChild(dialogOverlay);
            
            // 绑定事件
            const cancelBtn = dialogOverlay.querySelector('#dialog-cancel');
            const confirmBtn = dialogOverlay.querySelector('#dialog-confirm');
            
            const handleClose = () => {
                dialogOverlay.remove();
                style.remove();
            };
            
            cancelBtn.addEventListener('click', () => {
                handleClose();
                if (onCancel) onCancel();
            });
            
            confirmBtn.addEventListener('click', () => {
                handleClose();
                if (onConfirm) onConfirm();
            });
            
            // 点击背景关闭
            dialogOverlay.addEventListener('click', (e) => {
                if (e.target === dialogOverlay) {
                    handleClose();
                    if (onCancel) onCancel();
                }
            });
            
            // ESC键关闭
            document.addEventListener('keydown', function handleEscape(e) {
                if (e.key === 'Escape') {
                    handleClose();
                    if (onCancel) onCancel();
                    document.removeEventListener('keydown', handleEscape);
                }
            });
        }
        
        // 删除分群规则
        function deleteSegmentRule(id) {
            showConfirmationDialog(
                '确认删除',
                '确定要删除该分群规则吗？此操作不可恢复。',
                () => {
                    let segmentRules = JSON.parse(localStorage.getItem('userSegmentRules') || '[]');
                    segmentRules = segmentRules.filter(rule => rule.id !== id);
                    localStorage.setItem('userSegmentRules', JSON.stringify(segmentRules));
                    loadSegmentRules();
                    showNotification('分群规则已删除', 'success');
                }
            );
        }

        // 显示通知
        function showNotification(message, type = 'info') {
            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.textContent = message;
            
            // 设置样式
            Object.assign(notification.style, {
                position: 'fixed',
                top: '20px',
                right: '20px',
                padding: '12px 20px',
                borderRadius: '8px',
                backgroundColor: type === 'success' ? '#06d6a0' : type === 'error' ? '#ef476f' : '#118ab2',
                color: 'white',
                fontWeight: 'bold',
                boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                zIndex: '10000',
                transform: 'translateX(100%)',
                transition: 'transform 0.3s ease'
            });
            
            // 添加到页面
            document.body.appendChild(notification);
            
            // 显示通知
            setTimeout(() => {
                notification.style.transform = 'translateX(0)';
            }, 10);
            
            // 自动关闭
            setTimeout(() => {
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 3000);
        }

        // 初始化模拟数据
        function initMockData() {
            console.log('开始初始化模拟数据...');
            
            // 生成数据中心风险告警模拟数据
            generateMockAlertData();
            
            // 生成文件指纹库模拟数据
            generateMockFileFingerprints();
            
            // 生成分词词库模拟数据
            generateMockWordLibrary();
            
            // 生成用户分群标签模拟数据
            generateMockUserSegments();
            
            // 生成文件溯源任务模拟数据
            generateMockTraceTasks();
            
            // 初始化数据中心风险告警分析模块
            initDataAnalysisModule();
            
            // 初始化文件溯源分析模块
            initFileTraceModule();
            
            // 初始化文件指纹库和分词词库管理模块
            // 添加条件检查，确保函数已定义
            if (typeof initLibrariesModule !== 'function') {
                function initLibrariesModule() {
                    // 初始化文件指纹库
                    if (typeof initFileFingerprintLibrary === 'function') {
                        initFileFingerprintLibrary();
                    } else {
                        console.warn('initFileFingerprintLibrary函数未定义');
                    }
                    
                    // 初始化分词词库
                    if (typeof initWordSegmentationLibrary === 'function') {
                        initWordSegmentationLibrary();
                    } else {
                        console.warn('initWordSegmentationLibrary函数未定义');
                    }
                    
                    console.log('文件指纹库和分词词库模块初始化完成');
                }
            }
            initLibrariesModule();
            
            // 初始化用户分群标签和可视化展示模块
            // 添加条件检查，确保函数已定义
            if (typeof initUserSegmentModule !== 'function') {
                function initUserSegmentModule() {
                    try {
                        console.log('开始初始化用户分群标签和可视化模块');
                        
                        // 初始化用户分群标签管理函数
                        if (typeof initUserSegmentTags !== 'function') {
                            function initUserSegmentTags() {
                                console.log('用户分群标签管理函数初始化');
                                // 基本的占位实现，避免错误
                                try {
                                    const addBtn = document.querySelector('#add-segment-tag-btn');
                                    const searchBtn = document.querySelector('#search-segment-tag-btn');
                                    if (addBtn) addBtn.addEventListener('click', () => console.log('添加标签按钮点击'));
                                    if (searchBtn) searchBtn.addEventListener('click', () => console.log('搜索标签按钮点击'));
                                } catch (e) {
                                    console.warn('用户分群标签管理初始化过程中出现警告:', e);
                                }
                            }
                        }
                        initUserSegmentTags();
                        
                        // 初始化可视化图表函数
                        if (typeof initVisualizationCharts !== 'function') {
                            function initVisualizationCharts() {
                                console.log('可视化图表函数初始化');
                                // 基本的占位实现，避免错误
                                try {
                                    // 尝试初始化各种图表元素
                                    const chartContainers = document.querySelectorAll('.chart-container');
                                    chartContainers.forEach((container, index) => {
                                        console.log(`初始化图表容器 ${index + 1}`);
                                    });
                                } catch (e) {
                                    console.warn('可视化图表初始化过程中出现警告:', e);
                                }
                            }
                        }
                        initVisualizationCharts();
                        
                        // 初始化分群规则管理函数
                        if (typeof initSegmentRules !== 'function') {
                            function initSegmentRules() {
                                console.log('分群规则管理函数初始化');
                                // 基本的占位实现，避免错误
                                try {
                                    const ruleAddBtn = document.querySelector('#add-segment-rule-btn');
                                    if (ruleAddBtn) ruleAddBtn.addEventListener('click', () => console.log('添加规则按钮点击'));
                                } catch (e) {
                                    console.warn('分群规则管理初始化过程中出现警告:', e);
                                }
                            }
                        }
                        initSegmentRules();
                        
                        console.log('用户分群标签和可视化模块初始化完成');
                    } catch (error) {
                        console.error('用户分群模块初始化失败:', error);
                        if (typeof ToastUtils !== 'undefined' && typeof ToastUtils.error === 'function') {
                            ToastUtils.error('用户分群模块初始化失败，请刷新页面重试');
                        }
                    }
                }
            }
            initUserSegmentModule();
            
            console.log('模拟数据生成完成，模块初始化完成');
        }
        
        // 生成数据中心风险告警模拟数据
        function generateMockAlertData() {
            // 检查是否已有数据，避免重复生成
            if (!localStorage.getItem('alertRanking')) {
                const alertData = [];
                const dataCenters = ['华北数据中心', '华东数据中心', '华南数据中心', '西南数据中心', '东北数据中心'];
                const severities = ['低', '中', '高', '严重'];
                
                // 为每个数据中心生成模拟告警数据
                for (let i = 0; i < dataCenters.length; i++) {
                    const alertCount = Math.floor(Math.random() * 200) + 50;
                    const severity = severities[Math.floor(Math.random() * severities.length)];
                    const trend = Math.floor(Math.random() * 40) - 20; // -20% 到 +20% 的变化趋势
                    
                    alertData.push({
                        id: `dc-${i+1}`,
                        name: dataCenters[i],
                        alerts: alertCount,
                        severity: severity,
                        trend: trend
                    });
                }
                
                // 按告警数量排序
                alertData.sort((a, b) => b.alerts - a.alerts);
                
                // 保存到localStorage
                localStorage.setItem('alertRanking', JSON.stringify(alertData));
                
                // 保存汇总数据
                const totalAlerts = alertData.reduce((sum, dc) => sum + dc.alerts, 0);
                const focusAlerts = alertData[0].alerts; // 假设第一个是关注的数据中心
                const avgTrend = Math.floor(alertData.reduce((sum, dc) => sum + dc.trend, 0) / alertData.length);
                
                localStorage.setItem('alertSummary', JSON.stringify({
                    totalAlerts: totalAlerts,
                    focusAlerts: focusAlerts,
                    avgTrend: avgTrend
                }));
            }
        }
        
        // 生成文件指纹库模拟数据
        function generateMockFileFingerprints() {
            if (!localStorage.getItem('fileFingerprints')) {
                const fingerprints = [];
                const fileTypes = ['doc', 'docx', 'xls', 'xlsx', 'pdf'];
                const fileNames = ['项目计划书', '财务报表', '会议记录', '需求文档', '技术规范', '系统架构', '安全审计', '用户手册'];
                
                // 生成10个模拟文件指纹
                for (let i = 0; i < 10; i++) {
                    const fileName = fileNames[Math.floor(Math.random() * fileNames.length)];
                    const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)];
                    const hash = 'minhash_' + Math.random().toString(36).substring(2, 15);
                    const date = new Date();
                    date.setDate(date.getDate() - Math.floor(Math.random() * 30)); // 最近30天内的随机日期
                    
                    fingerprints.push({
                        id: `fp-${i+1}`,
                        filename: `${fileName}.${fileType}`,
                        hash: hash,
                        type: fileType,
                        status: '已处理',
                        createdAt: date.toISOString()
                    });
                }
                
                localStorage.setItem('fileFingerprints', JSON.stringify(fingerprints));
            }
        }
        
        // 生成分词词库模拟数据
        function generateMockWordLibrary() {
            if (!localStorage.getItem('wordSegmentationLibrary')) {
                const words = [];
                const categories = ['敏感词', '专业术语', '个人信息', '技术词汇', '业务词汇'];
                const wordList = [
                    {word: '密码', category: '敏感词'},
                    {word: '密钥', category: '敏感词'},
                    {word: '身份证', category: '个人信息'},
                    {word: '银行卡', category: '个人信息'},
                    {word: '用户认证', category: '技术词汇'},
                    {word: '数据加密', category: '技术词汇'},
                    {word: '分布式', category: '专业术语'},
                    {word: '微服务', category: '专业术语'},
                    {word: '安全审计', category: '业务词汇'},
                    {word: '风险评估', category: '业务词汇'}
                ];
                
                // 生成模拟词汇数据
                wordList.forEach((item, index) => {
                    words.push({
                        id: `word-${index+1}`,
                        word: item.word,
                        category: item.category,
                        weight: Math.floor(Math.random() * 5) + 1, // 1-5的权重
                        createdAt: new Date().toISOString()
                    });
                });
                
                localStorage.setItem('wordSegmentationLibrary', JSON.stringify(words));
            }
        }
        
        // 生成用户分群标签模拟数据
        function generateMockUserSegments() {
            if (!localStorage.getItem('userSegmentTags')) {
                const tags = [];
                const tagCategories = ['行为特征', '属性特征', '风险等级', '活跃度'];
                const tagList = [
                    {name: '高风险用户', category: '风险等级', count: 256},
                    {name: '活跃用户', category: '活跃度', count: 1254},
                    {name: '新注册用户', category: '属性特征', count: 892},
                    {name: '敏感操作用户', category: '行为特征', count: 342},
                    {name: '低频用户', category: '活跃度', count: 517},
                    {name: 'VIP用户', category: '属性特征', count: 189},
                    {name: '异常登录用户', category: '行为特征', count: 63},
                    {name: '中风险用户', category: '风险等级', count: 428}
                ];
                
                // 生成模拟标签数据
                tagList.forEach((tag, index) => {
                    tags.push({
                        id: `tag-${index+1}`,
                        name: tag.name,
                        category: tag.category,
                        count: tag.count,
                        createdAt: new Date().toISOString()
                    });
                });
                
                localStorage.setItem('userSegmentTags', JSON.stringify(tags));
                
                // 生成用户分群规则数据
                const rules = [
                    {
                        id: 'rule-1',
                        name: '高风险用户规则',
                        description: '识别登录异常或执行敏感操作频繁的高风险用户',
                        condition: '登录失败次数 > 5 OR 敏感操作 > 3',
                        priority: '高',
                        status: '启用',
                        createdAt: new Date().toISOString()
                    },
                    {
                        id: 'rule-2',
                        name: '活跃用户规则',
                        description: '筛选在过去一周内频繁使用系统的活跃用户',
                        condition: '近7天登录次数 > 10 AND 操作次数 > 50',
                        priority: '中',
                        status: '启用',
                        createdAt: new Date().toISOString()
                    },
                    {
                        id: 'rule-3',
                        name: '新注册用户规则',
                        description: '识别系统中的新注册用户，用于特定的新手引导和监控',
                        condition: '注册时间 < 30天',
                        priority: '低',
                        status: '启用',
                        createdAt: new Date().toISOString()
                    },
                    {
                        id: 'rule-4',
                        name: '异常登录用户规则',
                        description: '检测来自非常规IP地址或异地登录的用户',
                        condition: '异地登录 = true OR 异常IP = true',
                        priority: '高',
                        status: '启用',
                        createdAt: new Date().toISOString()
                    },
                    {
                        id: 'rule-5',
                        name: '低频用户规则',
                        description: '识别长期未活跃的用户账户',
                        condition: '近30天登录次数 = 0',
                        priority: '低',
                        status: '禁用',
                        createdAt: new Date().toISOString()
                    }
                ];
                
                localStorage.setItem('userSegmentRules', JSON.stringify(rules));
            }
        }
        
        // 生成文件溯源任务模拟数据
        function generateMockTraceTasks() {
            if (!localStorage.getItem('fileTraceTasks')) {
                const tasks = [];
                const methods = ['file-upload', 'content-fragment', 'word-segment'];
                const types = ['tag', 'content'];
                const statuses = ['已完成', '进行中', '失败'];
                const fileNames = ['敏感文件.docx', '客户资料.xlsx', '项目计划书.pdf', '技术文档.docx'];
                
                // 生成8个模拟溯源任务
                for (let i = 0; i < 8; i++) {
                    const method = methods[Math.floor(Math.random() * methods.length)];
                    const type = types[Math.floor(Math.random() * types.length)];
                    const status = statuses[Math.floor(Math.random() * statuses.length)];
                    const date = new Date();
                    date.setDate(date.getDate() - Math.floor(Math.random() * 15)); // 最近15天内的随机日期
                    
                    let fileName = '';
                    if (method === 'file-upload') {
                        fileName = fileNames[Math.floor(Math.random() * fileNames.length)];
                    } else {
                        fileName = method === 'content-fragment' ? '内容片段' : '分词内容';
                    }
                    
                    tasks.push({
                        id: `task-${i+1}`,
                        fileName: fileName,
                        method: method,
                        type: type,
                        status: status,
                        resultCount: status === '已完成' ? Math.floor(Math.random() * 20) + 1 : 0,
                        createdAt: date.toISOString()
                    });
                }
                
                // 按创建时间倒序排列
                tasks.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
                
                localStorage.setItem('fileTraceTasks', JSON.stringify(tasks));
            }
        }
        // 最终测试和验证函数
        function validateAllFeatures() {
            console.log('=== 开始功能完整性测试 ===');
            
            // 1. 检查localStorage数据是否正确加载
            const requiredKeys = ['traceTasks', 'wordLibrary', 'userSegments', 'fileFingerprints', 'segmentRules', 'alertData'];
            requiredKeys.forEach(key => {
                const data = localStorage.getItem(key);
                if (data && JSON.parse(data).length > 0) {
                    console.log(`✅ ${key}: 数据加载成功，共 ${JSON.parse(data).length} 条记录`);
                } else {
                    console.warn(`⚠️ ${key}: 数据为空或未加载`);
                }
            });
            
            // 2. 检查核心功能初始化
            try {
                // 检查DOM缓存功能
                if (typeof getElement === 'function' && domCache && Object.keys(domCache).length > 0) {
                    console.log('✅ DOM缓存功能: 正常');
                } else {
                    console.warn('⚠️ DOM缓存功能: 未正确初始化');
                }
                
                // 检查防抖函数
                if (typeof debounce === 'function') {
                    console.log('✅ 防抖函数: 正常');
                } else {
                    console.warn('⚠️ 防抖函数: 未正确初始化');
                }
                
                // 检查标签页功能
                const activeTab = document.querySelector('.tab.active');
                const activeContent = document.querySelector('.tab-content.active');
                if (activeTab && activeContent) {
                    console.log('✅ 标签页功能: 正常激活');
                } else {
                    console.warn('⚠️ 标签页功能: 未正确激活');
                }
                
                console.log('✅ 核心功能初始化: 正常');
            } catch (error) {
                console.error('❌ 核心功能初始化错误:', error);
            }
            
            // 3. 检查分群规则功能
            try {
                const segmentRules = JSON.parse(localStorage.getItem('segmentRules') || '[]');
                const hasDescriptionField = segmentRules.every(rule => rule.hasOwnProperty('description'));
                const hasNewRules = segmentRules.some(rule => rule.id === 'rule-4' || rule.id === 'rule-5');
                
                if (hasDescriptionField && hasNewRules) {
                    console.log('✅ 分群规则功能: 正常支持新规则和描述字段');
                } else {
                    console.warn('⚠️ 分群规则功能: 部分功能未正确实现');
                }
            } catch (error) {
                console.error('❌ 分群规则功能错误:', error);
            }
            
            // 4. 检查搜索功能防抖
            const searchFunctions = ['debouncedSearchSegmentRules', 'debouncedSearchFingerprint'];
            searchFunctions.forEach(funcName => {
                if (typeof window[funcName] === 'function') {
                    console.log(`✅ ${funcName}: 防抖功能正常`);
                } else {
                    console.warn(`⚠️ ${funcName}: 防抖功能未正确初始化`);
                }
            });
            
            console.log('=== 功能完整性测试完成 ===');
        }
        
        // 页面加载完成后运行测试
        window.addEventListener('load', () => {
            // 延迟执行测试，确保所有功能初始化完成
            setTimeout(() => {
                validateAllFeatures();
            }, 1000);
        });
        
        // 通知系统工具函数
        const ToastUtils = {
            container: null,
            
            init() {
                this.container = document.getElementById('toastContainer');
                if (!this.container) {
                    console.error('Toast container not found');
                }
            },
            
            createToast(message, type = 'info', duration = 3000) {
                if (!this.container) this.init();
                
                const toast = document.createElement('div');
                toast.className = `toast toast-${type}`;
                
                // 添加图标
                const icon = document.createElement('span');
                const iconMap = {
                    success: '✓',
                    error: '✕', 
                    warning: '⚠',
                    info: 'ℹ'
                };
                icon.textContent = iconMap[type] || 'ℹ';
                
                // 添加消息
                const messageSpan = document.createElement('span');
                messageSpan.textContent = message;
                
                // 添加关闭按钮
                const closeBtn = document.createElement('button');
                closeBtn.className = 'toast-close';
                closeBtn.textContent = '×';
                closeBtn.onclick = () => this.removeToast(toast);
                
                toast.appendChild(icon);
                toast.appendChild(messageSpan);
                toast.appendChild(closeBtn);
                
                this.container.appendChild(toast);
                
                // 显示toast
                setTimeout(() => toast.classList.add('show'), 10);
                
                // 自动关闭
                if (duration > 0) {
                    setTimeout(() => this.removeToast(toast), duration);
                }
                
                return toast;
            },
            
            removeToast(toast) {
                toast.classList.remove('show');
                setTimeout(() => {
                    if (toast.parentNode === this.container) {
                        this.container.removeChild(toast);
                    }
                }, 300);
            },
            
            success(message, duration) {
                return this.createToast(message, 'success', duration);
            },
            
            error(message, duration) {
                return this.createToast(message, 'error', duration);
            },
            
            warning(message, duration) {
                return this.createToast(message, 'warning', duration);
            },
            
            info(message, duration) {
                return this.createToast(message, 'info', duration);
            }
        };
        
        // 加载状态工具函数
        const LoadingUtils = {
            overlay: null,
            textEl: null,
            counter: 0,
            
            init() {
                this.overlay = document.getElementById('loadingOverlay');
                this.textEl = document.getElementById('loadingText');
                if (!this.overlay) {
                    console.error('Loading overlay not found');
                }
            },
            
            show(text = '加载中...') {
                if (!this.overlay) this.init();
                this.counter++;
                this.textEl.textContent = text;
                this.overlay.classList.add('active');
            },
            
            hide() {
                if (!this.overlay) this.init();
                this.counter = Math.max(0, this.counter - 1);
                if (this.counter === 0) {
                    this.overlay.classList.remove('active');
                }
            },
            
            // 执行异步操作并自动管理加载状态
            async withLoading(asyncFn, text = '处理中...') {
                this.show(text);
                try {
                    return await asyncFn();
                } finally {
                    this.hide();
                }
            }
        };
        
        // 替代alert的错误处理
        function showError(message) {
            ToastUtils.error(message, 5000);
        }
        
        // 替代简单提示的成功反馈
        function showSuccess(message) {
            ToastUtils.success(message, 3000);
        }
        
        // 初始化通知系统
        document.addEventListener('DOMContentLoaded', () => {
            ToastUtils.init();
            LoadingUtils.init();
        });
    </script>
</div>
    </body>
</html>